Get select with options (selectinload) using response schema #1527
-
First Check
Commit to Help
Example Codefrom pydantic import BaseModel
class Parent(SQLModel, table=True):
id: UUID = sm.Field(UUID, primary_key=True)
childs:List[Child]= sm.Relationship(
back_populates="parent"
)
class Child(SQLModel, table=True):
parent_id:UUID=sm.Field()
sa_column=sm.Column(
sm.ForeignKey("parentr.id")
)
parent: "Parent" = sm.Relationship(
back_populates="childs"
)
#read schemas
class IChildRead(BaseModel):
id:UUID
class IParentReadWithChilds(BaseModel):
childs:List[IChildRead] DescriptionWhat i want to get from pydantic response schema ? I want to get a query with select lazy options, using the schema of response, because this information already contains in relationships of pydantic models. The existance of property in pydantic model gives information about the need to use selectinload. Is there any solutions for it? Operating SystemLinux Operating System Detailsany SQLModel Versionany Python Versionany Additional Contextany |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
There are 2 ways to Child load with a selectin (or whatever type of lazy option):
childs:List[Child]= sm.Relationship(
back_populates="parent",
sa_relationship_kwargs: {"lazyload": "selectin"},
) Whenever you select Parent objects, the children will always be loaded.
If you want to be a bit more selective about when you do the selectin load, you can add it to the query: from sqlalchemy.orm import selectinload
all_parents = session.exec(select(Parent).options(selectinload(Parent.childs)).all() Pretty much anything you can do with the loads is described here: https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html |
Beta Was this translation helpful? Give feedback.
-
Any way to use this without type errors? I'm getting this complaint when I use the selectinload
|
Beta Was this translation helpful? Give feedback.
-
In version childs:List[Child]= sm.Relationship(
back_populates="parent",
sa_relationship_kwargs: {"lazy": "selectin"}, # lazy instead of lazyload
) |
Beta Was this translation helpful? Give feedback.
-
@cycledriver Thank you for your reply! But I have related question, in that case all childs will be loaded, what can be a problem if there are a lot of childs. Do you know if there is a way to limit childs, or add where condition or whatever to load only N childs? |
Beta Was this translation helpful? Give feedback.
-
Actually found a way:
|
Beta Was this translation helpful? Give feedback.
-
You can wrap your relationship's type declaration in persona_traits: Mapped[List[PersonaTrait]] = Relationship(back_populates="persona") That will shut Pyright up. |
Beta Was this translation helpful? Give feedback.
In version
0.0.21
Passinglazy
instead oflazyload
worked for me.