sqlalchemy foreign key relationship attributes

喜欢而已 提交于 2019-11-29 20:18:13
Paolo Casciello

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!