Filtering models by their many to many relationship #587
-
First Check
Commit to Help
Example Codefrom sqlmodel import SQLModel, Relationship, Field, select
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(workspace in User.workspaces) # -- this doesn't work!
...
class UserWorkspace(SQLModel, table=True):
user_id: int = Field(foreign_key='user.id')
workspace_id: int = Field(foreidgn_key='workspace.id')
class User(SQLModel, table=True):
id: int ...
username: str
logins: int
workspaces: list[Workspace] = Relationship(link_model=UserWorkspace)
class Workspace(SQLModel, table=True):
id: int ... DescriptionI can't find a way to filter models by their relationship if it is a x-to-many relationship. The example above tries to find Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.8 Python Version3.10.0 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
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(SQLModel, table=True):
id: int ...
username: str
logins: int
workspaces: list[Workspace] = Relationship(link_model=UserWorkspace)
class Workspace(SQLModel, table=True):
id: int ... In this modified code, the any_ method is used to filter the users by their workspace. The id attribute of the Workspace model is used to filter the users, and it is compared to the workspace.id attribute, which is the ID of the workspace passed to the find_users function. |
Beta Was this translation helpful? Give feedback.
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: