Skip to content Skip to sidebar Skip to footer

Issues With Initializing Tortoise Orm With Fastapi

i am having issue with tortoise orm and fastapi i have the following code from app.py; i have skipped some lines to make this concise app.py from fastapi import FastAPI, HTTPExcept

Solution 1:

As I said in the comments, you need to insert

Tortoise.init_models(models_list, "models")

before the following line

register_tortoise(
    app,
    db_url=config.DATABASE_URL,
    modules={"models": ["app.models"]},
    generate_schemas=True,
    add_exception_handlers=True,
)

Of course you'll have to change the "models" folder and name according to your configuration.

At the beginning it was also a problem for me as well, but the following github issue solved the problem

https://github.com/tortoise/tortoise-orm/issues/444

Also the docs provide the explanation

https://tortoise-orm.readthedocs.io/en/latest/search.html?q=early+init

UPDATE

Tortoise.init_models(models_list, "models")

models_list is the list (strings) of paths of the models that are to be considered. In your case, it'll be app.models.

The idea is to initialize and start preparing the models, before connecting to the database. This is a step required in order to make relations available in the pydantic models.

Here the API docs

https://tortoise-orm.readthedocs.io/en/latest/setup.html?highlight=init#tortoise.Tortoise.init_models

Post a Comment for "Issues With Initializing Tortoise Orm With Fastapi"