Cristofer Nava
Cristofer Nava

Reputation: 89

How to establish a many to many relationship in SQLAlchemy?

I'm trying to build a simple app where users can follow other users so, I have a table "Users" that has all the user's info, and since a user can follow many users and that user can have many followers we get a Many-to-Many relationship, so I created a linking table. Here's my code: enter image description here

As you can see the "UsersFollowing" table has composite Primary Key that is build from the Foreign Keys taken from the "User" table (user, and who is following).

Now I want to get the following: "Given a user id return all the users that follows".

I'm new in SQLAlchemy and I don't know how to get the result.

Upvotes: 0

Views: 573

Answers (1)

MatsLindh
MatsLindh

Reputation: 52822

If you're using the SQLAlchemy ORM, you should be able to get the users by issuing a join and filtering:

db_session.query(User)\
    .join(UsersFollowing, User.id == UsersFollowing.user_following_id)\
    .filter(UsersFollowing.user_id == <userid>)

Upvotes: 1

Related Questions