Describe the bug
Nesting related models by foreign key doesn't work for Tortoise Orm objects:
I have two models: Events and Tournament, and Event has a foreign key relation to Tournament. I want to select an event from the db and return it in my response such that the serialised event also contains the related tournament object nested in it:
{
"name": "my event",
"tournament": {
"name": "my tournament"
}
}
Whatever I tried, the best I could do is get the tournament_id in the serialised event.
To Reproduce
Steps to reproduce the behavior, preferably a small code snippet.
# models.py
class Tournament(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
class Event(Model):
name = fields.CharField(max_length=255)
tournament = fields.ForeignKeyField('models.Tournament', related_name='events')
# as per the https://tortoise-orm.readthedocs.io/en/latest/examples/fastapi.html example, but I also tried using the Pydantic models
Event_Pydantic = pydantic_model_creator(Event, name='Event', include=("name", 'tournament'))
Tournament_Pydantic = pydantic_model_creator(Tournament, name='Tournament')
# main.py
app = FastAPI()
register_tortoise(
app,
db_url=TORTOISE_ORM['connections']['default'],
modules={'models': ['models']},
generate_schemas=True,
add_exception_handlers=True,
)
@app.get('/events/', response_model=models.Event_Pydantic)
async def get_events():
return await models.Event_Pydantic.from_queryset_single(
models.Event.get(id=1).select_related('tournament')
)
Describe the bug Nesting related models by foreign key doesn't work for Tortoise Orm objects: I have two models: Events and Tournament, and Event has a foreign key relation to Tournament. I want to select an event from the db and return it in my response such that the serialised event also contains the related tournament object nested in it:
Whatever I tried, the best I could do is get the
tournament_id
in the serialised event.To Reproduce Steps to reproduce the behavior, preferably a small code snippet.
Expected behavior
Actual behaviour:
Additional context Add any other context about the problem here.