I have the following schema:
class UserBase(SQLModel):
username: str
class User(UserBase, table=True):
id: int | None = Field(primary_key=True)
channels: list['Channel'] = Relationship(back_populates='participants', sa_relationship_kwargs={'lazy': 'subquery'})
class UserOutput(UserBase):
id: int
channels: list['Channel']
I have an endpoint to read all users in the system.
@router.get('/user', response_model=??)
def read_users(...):
return all_users(...)
Now, if response_model = User
, there will be no channels
field in the response, however, when response_model = UserOutput
, channels
will be set and contain the right data. Why is that?
This happens because SQLModel modifies the way fields are collected so that Relationship
is not recognized as a field. If you think about it, it makes sense from ORM point of view, because this is not a real model field.
Try this example:
with Pydantic:
class A(BaseModel):
a: list = Relationship()
>>> A()
A(a=RelationshipInfo())
>>> A.__fields__
{'a': ModelField(name='a', type=list, required=False, default=RelationshipInfo())}
with SQLModel:
class B(SQLModel):
a: list = Relationship()
>>> B()
B()
>>> B.__fields__
{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With