Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship fields not showing up in FastAPI response

Tags:

fastapi

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?

like image 378
user2268997 Avatar asked Sep 20 '25 08:09

user2268997


1 Answers

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__
{}

like image 54
Vladimir Odaysky Avatar answered Sep 23 '25 12:09

Vladimir Odaysky