2017-02-16 97 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)