How can I filter joining table results ?
I have 3 tables:
User:
id: str
full_name: str
is_active: bool # NEED TO FILTER BY THIS
tags: Mapped[list["Tag"]] = relationship(
"Tag", secondary=user_tag, back_populates="users"
)
Tag:
id: str
name: str
users: Mapped[list["Tag"]] = relationship(
"User", secondary=user_tag, back_populates="tags", lazy="selectin"
)
user_tag = Table(
"user_tag",
Base.metadata,
Column("user_id", ForeignKey("user.id", ondelete="CASCADE"), primary_key=True),
Column("tag_id", ForeignKey("tag.id", ondelete="CASCADE"), primary_key=True),
)
I’m getting all tags like this:
all_tags= await session.scalars(select(Tag))
If I want to get all users for this tag, I do like this:
all_tags_with_users = await session.scalars(select(Tag).join(Tag.users)
But how can I join only active users ? Where I should put where
condition ? I assume it should be like this:
all_tags_with_only_active_users = await session.scalars(select(Tag).join(Tag.users, onclause=Tag.users.contains(User.id) & Tag.users.is_active=True)
Use PropComparator.and_ to add an on
clause.
select(Tag).join(
Tag.users.and_(Users.is_active == True)
)
See Combining Relationship with Custom ON Criteria in the SQLAlchemy docs for more.