peewee外键错误

时间:2014-12-26 15:51:37

标签: python mysql peewee

我正在尝试使用peewee为我现有的数据库创建一个简单的模型。

我正在处理的数据库在this paper中描述。

我已经使用pwiz生成了一个工作正常的模型,但它没有为我创建启用加入的外键。因此我编辑了模型,看起来像这样:

from peewee import *

database = MySQLDatabase('enron', **{'password': '...', 'user': 'root'})


class UnknownField(object):
    pass


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


class Employee(BaseModel):
    email = CharField(db_column='Email_id', unique=True)
    eid = PrimaryKeyField()    
    class Meta:
        db_table = 'employeelist'


class Message(BaseModel):
    mid = PrimaryKeyField()
    sender = ForeignKeyField(Employee,
                             related_name='messages',
                             to_field='email')  # was CharField() before my edit

    class Meta:
        db_table = 'message'

然而,当我尝试跑步时:

for message in Message.select():
    print message.mid

我收到错误:

Traceback (most recent call last):
  File "DBModelEnron.py", line 62, in <module>
    for message in Message.select():
  File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2514, in __iter__
    return iter(self.execute())
  File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2507, in execute
    self._qr = ResultWrapper(model_class, self._execute(), query_meta)
  File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2203, in _execute
    return self.database.execute_sql(sql, params, self.require_commit)
  File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2833, in execute_sql
    self.commit()
  File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2688, in __exit__
    reraise(new_type, new_type(*exc_value.args), traceback)
  File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2825, in execute_sql
    cursor.execute(sql, params or ())
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
peewee.OperationalError: (1054, "Unknown column 't1.sender_id' in 'field list'")

我发现了类似的问题here,但是我已经定义了正确的PrimaryKey。

1 个答案:

答案 0 :(得分:3)

只需在外键中添加db_column=''

sender = ForeignKeyField(Employee,
                         db_column='sender',  # Added this.
                         related_name='messages',
                         to_field='email')  # was CharField() before my edit