没有在sqlalchemy 上查询到类似的功能,自己试着这样来实现:
class Friendship(Base): __tablename__ = 'friendship' id = Column(Integer,primary_key=True) me = Column(Integer,ForeignKey('users.id')) friend = Column(Integer,ForeignKey('users.id')) def __init__(self,me,friend): self.me = me self.friend = friend def check_existing(self): existing = session.query(Friendship).filter_by(me=self.me,friend=self.friend).first() if not existing: friendship = Friendship(self.me,self.friend) else: friendship = existing session.close() return friendship
使用则如下:
friendship = Friendship(self.from_user_id,self.friend_id) friendship = friendship.check_existing() session.add(friendship) session.commit() session.close()