I have a model representing user and I want to create a relationship between users representing that they are friends. My functional model with association table and methods to list all the friends look like this
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
The problem is that I need to implement asking for frienship and status pending before confirmation (just like you know it from Facebook) so it is necesarry to add an extra column to the frienship table. According to the SQLAlchemy tutorial I should create an Association Object but how to make it self referential again?
Or is it possible to just add this column to my current frienship table and access and change the status value there somehow?
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…