modelfastapiinittortoise-orm

Fastapi with tortoise-orm models early init models still not found


I am new to API dev, and I am trying to use tortoise-orm with fastapi but with a bit different folder structure (for user model for example src-> models->user.py): project structure

The main.py is located in the src folder and the issue occurs when I try to utilise the Tortoise models early init before register_tortoise like in (Model Relationships not showing in Tortoise-ORM + FastAPI). The result is models are still not found.

The main issue started when related_fields wasn't included in results and I am struggling with the solution itself in the database config file.

import importlib
from fastapi import FastAPI
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise

mdls=importlib.import_module("models")

#for mysql database
def get_mysql_db_uri(*, user, host, db_name):
    return f'mysql://{user}@{host}:3306/{db_name}'
#for sqlite database
def get_sqlite_db_uri( db_name_with_extension):
    return f'sqlite://{db_name_with_extension}'

def setup_database(app: FastAPI):
    Tortoise.init_models(["models"], 'models')
    register_tortoise(
        app,
        db_url="sqlite://testtort.db",
        modules={
            'models': [
                "models" 
            ],
            "default_connection": "default",
        },
        generate_schemas=True,
        add_exception_handlers=True,
        
    )
    Tortoise.init_models(["models"], 'models')# i've tryed Tortoise.init_models(["models.user","models.task","models.client"], 'models')

I also tried modules={'models': ["models.user","models.task","models.client"], if I use 'models':["models"] in both. The app starts but no database is created and no related fields for foreign key are showing.

Is the issue in the structure / models paths? I also found that using src.models.user didn't work as well.

I then tried applying the solution of (Fastapi/Tortoise early model init) (Model Relationships not showing in Tortoise-ORM + FastAPI)

Update: I was able to run the app by removing the default connection from the database configuration file, but no related fields are showing until now.


Solution

  • i've found the solution , a couple of things to : 1- remove Default Connexion from database setup 2- put Tortoise.init_models(["models.user","models.task","models.client"], 'models') on the top of each pydantic schema file (before creating dypandic models)