Self-Referential Association Relationship SQLalchemy

后端 未结 4 1270
南笙
南笙 2020-12-17 03:39

In my flask application with flask-sqlalchemy i need to create association between two contact here is my Contact model

class Contact(db.Model):         


        
4条回答
  •  离开以前
    2020-12-17 03:42

    Self-referential many-to-many relationship with Association Object.

    User Class:

    class User(Base):
        __tablename__ = "User"
        id = Column(String(36), primary_key=True, default=lambda : str(uuid1()))
    

    Association Class:

    class UserIgnore(Base):
        __tablename__ = "UserIgnore"
        id = Column(String(36), primary_key=True, default=lambda : str(uuid1()))
    
        ignored_by_id = Column("ignored_by_id", String(36), ForeignKey("User.id"), primary_key=True)
        ignored_by = relationship("User", backref="ignored_list",  primaryjoin=(User.id == ignored_by_id))
        ignored_id = Column("ignored_id", String(36), ForeignKey("User.id"), primary_key=True)
        ignored = relationship("User", backref="ignored_by_list",  primaryjoin=(User.id == ignored_id))
    

    Access the relationship objects with

    someUser.ignored_list
    

    or

    someUser.ignored_by_list
    

    Thanks to Sean

提交回复
热议问题