Skip to content

Filtering models by their many to many relationship #587

Discussion options

You must be logged in to vote

To filter models by their relationship in a x-to-many relationship, you can use the any_ method of the relationship attribute. Here's how you can modify your code to filter users by their workspace:

from sqlmodel import SQLModel, Relationship, Field, select, any_

def find_users(workspace: Workspace, min_logins: int):
  """ find all users of the workspace with at least min_logins logins """
  statement = select(User).where(User.logins >= min_logins) \
                           .where(User.workspaces.any_(id=workspace.id))
  ...

class UserWorkspace(SQLModel, table=True):
  user_id: int = Field(foreign_key='user.id')
  workspace_id: int = Field(foreign_key='workspace.id')

class User(SQLM…

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@thedamnedrhino
Comment options

@antont
Comment options

@thedamnedrhino
Comment options

@antont
Comment options

@vlntsolo
Comment options

Answer selected by thedamnedrhino
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
4 participants