1

我将如何在 SQLAlchemy 和 Flask 中制作 Facebook 风格的消息传递系统(基于此http://www.9lessons.info/2013/05/message-conversation-database-design.html )?这是我目前的模型,但我不断收到不明确的外键错误,我假设基于我的对话表。

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(12), unique=False)
    conversation = db.relationship('Conversation',backref='user',lazy='dynamic')
    conversation_reply = db.relationship('Conversation_Reply',backref='user',lazy='dynamic')

class Conversation(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user1 = db.Column(db.Integer, db.ForeignKey("user.id"))
    user2 = db.Column(db.Integer, db.ForeignKey("user.id"))
    timestamp = db.Column(db.DateTime)
    conversation_reply = db.relationship('Conversation_Reply',backref='conversation',lazy='dynamic')

class Conversation_Reply(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    reply = db.Column(db.Text)
    user_id_fk = db.Column(db.Integer, db.ForeignKey("user.id"))
    time = db.Column(db.DateTime)
    c_id_fk = db.Column(db.String(11), db.ForeignKey("conversation.id"))
4

1 回答 1

1

如果用户是 user1 或 user2,您可能希望指定加入条件以获取两个对话,您可以执行以下操作:

class User(db.Model):
    # ...
    # Converstations where either user1 or user2 is this user.
    all_conversations = db.relationship('Conversation',
        primaryjoin='or_(User.id == Conversation.user1_id, User.id == ' \
        'Conversation.user2_id)', lazy='dynamic')
    # Replies where this is this user.
    replies = db.relationship("Reply", backref="user")

class Conversation(db.Model):
    # ...
    user1_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    user2_id = db.Column(db.Integer, db.ForeignKey("user.id"))        
    user1 = db.relationship('User', foreign_keys=[user1_id], 
        backref='conversations_as_user1')       
    user2 = db.relationship('User', foreign_keys=[user2_id], 
        backref='conversations_as_user2')
    # Replies to this conversation.
    replies = db.relationship("Reply", backref="conversation")

class Reply(db.Model):
    # ...
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    conversation_id = db.Column(db.Integer, db.ForeignKey("conversation.id"))

您可能希望将 user1 和 user2 更改为from_userto_user基于谁开始对话。

于 2013-08-11T00:10:23.813 回答