Skip to content
Advertisement

Fastapi/Tortoise early model init

I have the following implementation with fastapi.

My current problem is that I can’t for the life of me do an early init on the tortoise models to get the relationship back in the schema.

I’ve tried dumping the following line basically everywhere and it just doesn’t seem to work.

JavaScript

i’ve also tried using prefetch_related this way but that doesn’t work either

JavaScript

I’ve been googling around for hours and haven’t found a concrete answer/way to get this to properly work.

Folder structure:

JavaScript
main.py
JavaScript
database/database.py
JavaScript
models/user.py
JavaScript
models/group.py
JavaScript
routers/group_router.py
JavaScript

As you can see that last line GetGroup.schema(), never returns the relationship.

I tried capturing the logs while the container is starting and got the following

JavaScript

mind you it does that for a few seconds and then the application starts correctly, i’ve also tried separating the pydantic models creation in a separate folder called ‘schema’ and that didn’t do anything either

Advertisement

Answer

so i’ve finally found an answer and i’m gonna leave it here in case some poor soul stumbles upon this question

the trick was to move

JavaScript

to the top of the main.py file

and add

JavaScript

below the init_db() function so that it’s called upon before the register_tortoise function executes and all the models are initialized

Info source: https://stackoverflow.com/a/65881146/13637905

Advertisement