Swap 2x for loop to sqlalchemy select

Viewed 11

(I am sorry for the title, but I can't find a better way to describe this)

The problem is simple, there are users and groups which have many to many relationship. When choosing an user, I want to get everyone who belongs to his groups. Example:

GROUP A: user_1, user_2, user_3 
GROUP B: user_1,         user_3
GROUP C:         user_2, user_3, user_4

When choosing user_1 I should get [user_2, user_3]

I wish to use a sqlalchemy select to get above results. Python code:

all_users = []
for group in self.groups: # self is the current user
    for user in group.users:
         if user not in all_users:
            all_users.append(user)

So, something like:

users = db.scalars(
    select(models.User).where( ..... )).fetch_all()

Any ideas would be appreciated, I tried something fitting from the docs, but that didn't work out.

0 Answers
Related