在sqlalchemy中具有额外字段的自引用数据库

时间:2014-09-25 09:16:52

标签: python sqlalchemy

我想使用Flask和SQLAlchemy为我的消息传递系统编写一个自引用数据库结构。 表非常简单:

class User(db.Model):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    messages = db.relationship(...)

    def addMessage (self, friend, message):
       ...
       self.messages.append(friend)
       return self

和消息表是:

class Message (db.Model):
    __tablename__ = 'message'

    id = db.Column(db.Integer, primary_key=True)
    emmiter_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    receiver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    text = db.Column(db.Text)

我想知道与user表的关系如何? 以及如何在message表上插入数据?

这是我在user表中写的关系,但它不起作用:

messages = db.relationship('User',
    secondary = Message,
    primaryjoin = (Message.emmiter_id == id),
    secondaryjoin = (Message.receiver_id == id),
    backref = db.backref('correspondence', lazy = 'dynamic'),
    lazy = 'dynamic')

1 个答案:

答案 0 :(得分:0)

在解决了这个问题后,我在用户表和消息表之间找到了带有primaryjoin的解决方案。这是工作代码

# Messaging system table
class Message(db.Model):
    __tablename__ = 'message'

    emmiter_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    text = db.Column(db.Text, nullable=False)

和用户表格如下:

class User (db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    inbox = db.relationship('Message',backref='sender', primaryjoin=id==Message.emmiter_id)
    outbox = db.relationship('Message',backref='receiver', primaryjoin=id==Message.recipient_id)

以下是如何在消息表中添加消息:

message = Message(text="dsf", sender=sender , receiver=receiver)