sqlalchemy foreign key relationship attributes

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)