-
First Check
Commit to Help
Example Codeclass ChildBase(SQLModel):
name: str
parent_id: int | None = Field(default=None, foreign_key="parent.id")
class Child(ChildBase, table=true):
id: int | None = Field(default=None, primary_key=True)
class ParentBase(SQLModel):
name: str
class Parent(ParentBase, table=true):
id: int | None = Field(default=None, primary_key=True)
children: list["Child"] = Relationship(back_populates="parent")
class ParentRead(ParentBase):
children = list["Child"] DescriptionI want to read the parent with the number of related children, but I don't want to read the child content. For example, something like that
Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.8 Python Version3.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Why not just do "count/scalar" on DB when needed instead of creating seperate col for it? |
Beta Was this translation helpful? Give feedback.
-
I would also recommend not solving this in the database, but with Pydantic by upgrading to the latest SQLModel that supports Pydantic V2. You would then be able to define a model that is transforming your database Below an example for a computed field if the from pydantic import computed_field
class ParentRead(ParentBase):
@computed_field
@property
def children_counter(self) -> int:
return len(self.children) |
Beta Was this translation helpful? Give feedback.
I would also recommend not solving this in the database, but with Pydantic by upgrading to the latest SQLModel that supports Pydantic V2. You would then be able to define a model that is transforming your database
ParentRead
utilizing computed fields with some minor adjustments.Below an example for a computed field if the
Read
model inherits the list of children: