Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into MySQL table using peewee raises "unknown column" exception

I have the following script:

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)

table locations has few rows, table units is empty. When I try to start it, I keep getting exception:

(1054, "Unknown column 'location_id_id' in 'field list'")

What am I doing wrong?

Here is part of SQL script for creating table:

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;

Thank you in advance!

like image 395
mangolier Avatar asked Apr 17 '13 16:04

mangolier


1 Answers

If you want to explicitly specify a column, use db_column:

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

This is documented: http://peewee.readthedocs.org/en/latest/peewee/models.html#field-types-table

like image 166
coleifer Avatar answered Sep 17 '22 22:09

coleifer