【发布时间】:2014-09-30 09:30:08
【问题描述】:
我有一个代表用户的模型,我想在代表他们是朋友的用户之间创建关系。我的带有关联表和列出所有朋友的方法的功能模型如下所示
friendship = db.Table('friend',
db.Column('id', db.Integer, primary_key=True),
db.Column('fk_user_from', db.Integer, db.ForeignKey('user.id'), nullable=False),
db.Column('fk_user_to', db.Integer, db.ForeignKey('user.id'), nullable=False)
)
class User(db.Model):
...
...
friends = db.relationship('User',
secondary=friendship,
primaryjoin=(friendship.c.fk_user_from==id),
secondaryjoin=(friendship.c.fk_user_to==id),
backref = db.backref('friend', lazy = 'dynamic'),
lazy = 'dynamic')
def list_friends(self):
friendship_union = db.select([
friendship.c.fk_user_from,
friendship.c.fk_user_to
]).union(
db.select([
friendship.c.fk_user_to,
friendship.c.fk_user_from]
)
).alias()
User.all_friends = db.relationship('User',
secondary=friendship_union,
primaryjoin=User.id==friendship_union.c.fk_user_from,
secondaryjoin=User.id==friendship_union.c.fk_user_to,
viewonly=True)
return self.all_friends
问题是我需要在确认之前实现询问友谊和待定状态(就像你从 Facebook 知道的那样),所以有必要在友谊表中添加一个额外的列。根据SQLAlchemy tutorial,我应该创建一个关联对象,但如何让它再次自引用?
或者是否可以将此列添加到我当前的友谊表中并以某种方式访问和更改那里的状态值?
谢谢
【问题讨论】:
标签: python database database-design sqlalchemy flask-sqlalchemy