2017-02-16 95 views
0

我正在使用反射来生成两个类。一个表示消息,并且拥有发送/接收实体(它们可以是公司或人员)的表中有两个外键。与Flask-SQLAlchemy和反射的关系

鉴于两个外键,我想创建相应的关系,这听起来应该很容易,但我无法让它工作。

我的代码如下所示:

class Entity(db.Model): 
    __tablename__ = 'Entity' 
    __table_args__ = { 
     'autoload': True, 
     'schema': 'msg', 
     'autoload_with': db.engine 
    } 

class FileData(db.Model): 
    __tablename__ = 'FileData' 
    __table_args__ = { 
     'autoload': True, 
     'schema': 'msg', 
     'autoload_with': db.engine 
    } 
    sender = db.relationship('Entity', foreign_keys='SenderId') 
    receiver = db.relationship('Entity', foreign_keys='ReceiverId') 

它失败,出现以下消息:

InvalidRequestError: When initializing mapper Mapper|FileData|FileData, expression 
'SenderId' failed to locate a name ("name 'SenderId' is not defined"). If this is a 
class name, consider adding this relationship() to the <class '__main__.FileData'> 
class after both dependent classes have been defined. 

我不知道怎么利用这一点,因为“SenderId”绝对是一个在桌子上的列,我没有问题在代码的其他部分访问它。

+0

它是FileData和Entity之间的一对一关系吗? – Cicero

+0

西塞罗,它不是。每个FileData条目都有1个发送者和1个接收者,都来自实体表......但是每个实体表条目将是许多FileData条目的发送者或接收者。 – user3199144

+0

好的,我试图弄清楚 - 但是很难。但有一点我可以告诉你,你应该在foreign_keys定义中使用小写。例如:'sender.id' /'receiver.id' – Cicero

回答

0

如果关系是在定义之外添加的,它会起作用。它看起来像允许它首先运行反射,然后看到SenderId和ReceiverId列。像这样:

class Entity(db.Model): 
    __tablename__ = 'Entity' 
    __table_args__ = { 
     'autoload': True, 
     'schema': 'msg', 
     'autoload_with': db.engine 
    } 

class FileData(db.Model): 
    __tablename__ = 'FileData' 
    __table_args__ = { 
     'autoload': True, 
     'schema': 'msg', 
     'autoload_with': db.engine 
    } 

FileData.sender = db.relationship('Entity', foreign_keys=FileData.SenderId) 
FileData.receiver = db.relationship('Entity', foreign_keys=FileData.ReceiverId)