两个表之间的关系,一个在flask-sqlalchemy中有2个外键

时间:2014-12-16 18:45:23

标签: python database sqlalchemy relationship flask-sqlalchemy

我有两个表代表用户和消息的表,如下所示:

class Users (db.Model):
    UserId = db.Column(db.INTEGER, primary_key=True,autoincrement=True)
    UserName = db.Column(db.String(25),nullable=False, unique=True)
    Email = db.Column(db.String,nullable=False,unique=True)

class Messages (db.Model):
    MessageId = db.Column(db.INTEGER,primary_key=True,autoincrement=True)
    SenderId = db.Column(db.INTEGER,db.ForeignKey('Users.UserId'),nullable=False)
    ReceiverId = db.Column(db.INTEGER,db.ForeignKey('Users.UserId'),nullable=False)
    Message = db.Column(db.String,nullable=False)

我想知道如果我想在Users类中编写以下内容:

  

db.relationship('Messages',backref ='MessageSender',lazy ='dynamic'#this return message sender。

     

db.relationship('Messages',backref ='MessageReceiver',lazy ='dynamic'#this返回消息接收者。

我该如何指定?这样我可以反映两个外键吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

下面应该有效:

class Messages(db.Model):
    MessageId = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    SenderId = db.Column(db.INTEGER, db.ForeignKey('users.UserId'), nullable=False)
    ReceiverId = db.Column(db.INTEGER, db.ForeignKey('users.UserId'), nullable=False)
    Message = db.Column(db.String, nullable=False)

    # define relationships
    sender = db.relationship(Users, foreign_keys=[SenderId], backref='sent')
    receiver = db.relationship(Users, foreign_keys=[ReceiverId], backref='received')

用法示例:

u0 = Users(UserName='Lila')
u1 = Users(
    UserName='John',
    sent=[Messages(Message='hi', receiver=u0)]
)