简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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