sqlalchemy foreign key relationship attributes

后端 未结 1 1389
挽巷
挽巷 2020-12-07 16:54

I have a User table and a Friend table. The Friend table holds two foreign keys both to my User table as well as a status field. I am trying to be able to call attributes

相关标签:
1条回答
  • 2020-12-07 17:23

    First, if you're using flask-sqlalchemy, why are you using directly sqlalchemy instead of the Flask's db.Model?

    I strongly reccomend to use flask-sqlalchemy extension since it leverages the sessions and some other neat things.

    Creating a proxy convenience object is straightforward. Just add the relationship with it in the Friend class.

    class Friend(Base):
        __tablename__ = 'friend'
    
        user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
        friend_id = Column(Integer, ForeignKey(User.id), primary_key=True)
        request_status = Column(Boolean)
    
        user = relationship('User', foreign_keys='Friend.user_id')
        friend = relationship('User', foreign_keys='Friend.friend_id')
    

    SQLAlchemy will take care of the rest and you can access the user object simply by:

    name = friend.user.name
    

    If you plan to use the user object every time you use the friend object specify lazy='joined' in the relationship. This way it loads both object in a single query.

    0 讨论(0)
提交回复
热议问题