FastAPI SQLAlchemy relationship models loading

Viewed 1132

I'm starting with FastAPI and SQLAlchemy, and I have a question about loading models in the correct order to satisfy SQLAlchemy models relationship. I've got two models, Profile and Account:

Profile:

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

from project.core.database import Base


class Profile(Base):
    __tablename__ = "profiles"

    id = Column(Integer, primary_key=True)
    name = Column(String(10), nullable=False)
    slug = Column(String(10), nullable=False)
    order = Column(Integer, unique=True, nullable=False)

    accounts = relationship(
        "Account", foreign_keys="[Account.profile_id]", back_populates="profile"
    )

Account:

from sqlalchemy import Column, Integer, String, LargeBinary, ForeignKey
from sqlalchemy.orm import relationship

from project.core.database import Base


class Account(Base):
    __tablename__ = "accounts"

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)
    email = Column(String(255), nullable=False)
    password = Column(LargeBinary, nullable=False)

    profile_id = Column(Integer, ForeignKey("profiles.id"))
    profile = relationship(
        "Profile", foreign_keys=[profile_id], back_populates="accounts"
    )

And in my project.core.database file, I created a method to import the models, since I was having issues with models not being located when the relationship was attempted to be made.

def import_all():
    import project.models.profile
    import project.models.account


def init_db():
    import_all()

My question is, is there a smarter way to load the models in the correct order? Because now I only have two models, but soon it can grow to dozens of models and I think this will become such a monster to manage. I looked for resources and examples, but everything I found created the models in a single file.

Thanks in advance!

1 Answers

Let's take a look at full-stack-fastapi-postgresql, a boilerplate template created by the author of FastAPI:

base.py

from app.db.base_class import Base 
from app.models.item import Item  
from app.models.user import User

init_db.py

from app.db import base  # noqa: F401 import db models

# make sure all SQL Alchemy models are imported (app.db.base) before initializing DB
# otherwise, SQL Alchemy might fail to initialize relationships properly
# for more details: https://github.com/tiangolo/full-stack-fastapi-postgresql/issues/28


def init_db(db: Session) -> None:
    ...

So, as you can see it's a polucalar way to import models, here you can find additional discussion: https://github.com/tiangolo/full-stack-fastapi-postgresql/issues/28

Related