简体   繁体   English

与Flask-SQLAlchemy和反射的关系

[英]Relationships with Flask-SQLAlchemy and reflection

I'm using reflection to generate two classes. 我正在使用反射生成两个类。 One represents messages and has 2 foreign keys to a table that holds the Sending/Receiving Entity (they can be companies or people). 一个代表消息,并具有指向表的两个外键,该表保存发送/接收实体(它们可以是公司或个人)。

Given the two foreign keys, I want to create the corresponding relationships, this sounds like it should be easy, but I can't get it to work. 给定两个外键,我想创建对应的关系,这听起来应该很简单,但是我无法使其正常工作。

My code looks like this: 我的代码如下所示:

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')

It fails with the following message: 失败并显示以下消息:

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.

I'm not sure what to make of this, since 'SenderId' is definitely one of the columns on the table, and I have no problem accessing it in other parts of the code. 我不确定该怎么做,因为“ SenderId”绝对是表中的列之一,并且在代码的其他部分访问它也没有问题。

It does work if the relationships are added outside of the definition. 如果将关系添加到定义之外,则它确实起作用。 It looks like this allowed it to run the reflection first and then see the SenderId and ReceiverId columns. 看起来像这样允许它首先运行反射,然后查看SenderId和ReceiverId列。 Like so: 像这样:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM