Skip to content Skip to sidebar Skip to footer

Model Relationships Not Showing In Tortoise-orm + Fastapi

I was playing around with FastAPI using Tortoise-ORM for it's orm and encountered a problem. Specifically, I cannot return a relationship in the model. Here is my application struc

Solution 1:

Thanks to @alex_noname I could achieve this.

First, separate the pydantic schemas from the models.py.

.
├── Dockerfile
├── LICENSE
├── Pipfile
├── Pipfile.lock
├── README.md
├── app
│   ├── contacts
│   │   ├── __init__.py
│   │   ├── main.py
│   │   ├── models.py
│   │   ├── routers.py
│   │   └── schemas.py  <- new
│   ├── main.py
│   ├── resources
│   │   ├── __init__.py
│   │   ├── constants.py
│   │   ├── core_model.py
│   │   ├── database.py
│   │   └── middlewares.py
│   └── users
│       ├── __init__.py
│       ├── main.py
│       ├── models.py
│       ├── routers.py
│       └── schemas.py  <- new
└── docker-compose.yml

app/users/schemas.py

from tortoise.contrib.pydantic import pydantic_model_creator

from .models import User


User_Pydantic = pydantic_model_creator(User, name='User')
UserIn_Pydantic = pydantic_model_creator(
    User, name='UserIn', exclude_readonly=True)

app/contacts/schemas.py

from tortoise.contrib.pydantic import pydantic_model_creator

from .models import Contact


Contact_Pydantic = pydantic_model_creator(Contact, name='Contact')
ContactIn_Pydantic = pydantic_model_creator(
    Contact, name='ContactIn', exclude_readonly=True)

Then, in app/resources/database.py where we are setting up the tortoise-orm, call init_models.

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


defget_db_uri(*, user, password, host, db):
    returnf'postgres://{user}:{password}@{host}:5432/{db}'defsetup_database(app: FastAPI):
    register_tortoise(
        app,
        db_url=get_db_uri(
            user='postgres',
            password='postgres',
            host='db',  # docker-composeのservice名
            db='postgres',
        ),
        modules={
            'models': [
                'app.users.models',
                'app.contacts.models',
            ],
        },
        # modules={"models": ["_models_"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )


Tortoise.init_models(['app.users.models', 'app.contacts.models'], 'models')  # <- added

and that's it! This worked like a charm.

Post a Comment for "Model Relationships Not Showing In Tortoise-orm + Fastapi"