使用peewee插入MySQL表会引发"未知列"异常

Ken*_*uat 4 python mysql peewee

我有以下脚本:

from peewee import *

db = MySQLDatabase('database', user='root')

class BaseModel(Model):
    class Meta:
        database = db

class Locations(BaseModel):
    location_id = PrimaryKeyField()
    location_name = CharField()

class Units(BaseModel):
    unit_id = PrimaryKeyField()
    unit_num = IntegerField()
    location_id = ForeignKeyField(Locations, related_name='units')

db.connect()

for location in Locations.select():
    for pod_num in range (1, 9):
        unit = Units.create(unit_num=pod_num, location_id=location.location_id)
Run Code Online (Sandbox Code Playgroud)

表位置有几行,表单位为空.当我尝试启动它时,我会一直异常:

(1054, "Unknown column 'location_id_id' in 'field list'")
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

以下是用于创建表的SQL脚本的一部分:

CREATE  TABLE IF NOT EXISTS `database`.`units` (
  `unit_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `unit_num` TINYINT UNSIGNED NOT NULL ,
  `location_id` INT UNSIGNED NOT NULL ,
  PRIMARY KEY (`unit_id`) ,
  UNIQUE INDEX `ID_UNIQUE` (`unit_id` ASC) ,
  INDEX `location_idx` (`location_id` ASC) ,
  CONSTRAINT `location_id`
    FOREIGN KEY (`location_id` )
    REFERENCES `database`.`locations` (`location_id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;
Run Code Online (Sandbox Code Playgroud)

先感谢您!

col*_*fer 6

如果要显式指定列,请使用db_column:

class Units(BaseModel):
    unit_id = PrimaryKeyField()
    unit_num = IntegerField()
    location_id = ForeignKeyField(Locations, db_column='location_id', related_name='units')
Run Code Online (Sandbox Code Playgroud)

记录在案:http://peewee.readthedocs.org/en/latest/peewee/models.html#field-types-table