SQLAlchemy中的Facebook风格消息系统

时间:2013-08-10 20:10:08

标签: sql sqlalchemy flask flask-sqlalchemy

如何在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"))

1 个答案:

答案 0 :(得分: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