tortoise / tortoise/tortoise-orm

Nested serialised objects from tortoise orm

Open
#1,139 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

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')
    )

Expected behavior

{
  "name": "game one"
  "tournament": {
    "name": "my tournament"
  }
}

Actual behaviour:

{
  "name": "game one"
}

Additional context
Add any other context about the problem here.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with models.py and main.py, focusing on pydantic_model_creator, Event_Pydantic.from_queryset_single, and the select_related('tournament') query. Reproduce the response for /events/ and trace why the related tournament is omitted. Done means the response includes the nested tournament name as shown in the expected JSON.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, python
Domain
backend, database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.