FastAPI SQLAlchemy 关系模型加载

Mar*_*elo 5 python sqlalchemy fastapi

我从 FastAPI 和 SQLAlchemy 开始,我有一个关于以正确的顺序加载模型以满足 SQLAlchemy 模型关系的问题。我有两个模型,个人资料和帐户:

轮廓:

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"
    )

Run Code Online (Sandbox Code Playgroud)

帐户:

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"
    )

Run Code Online (Sandbox Code Playgroud)

在我的project.core.database文件中,我创建了一种导入模型的方法,因为在尝试建立关系时,我遇到了无法找到模型的问题。

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


def init_db():
    import_all()
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有更智能的方法来按正确的顺序加载模型?因为现在我只有两个模型,但很快它就会增长到数十个模型,我认为这将成为管理的一个庞然大物。我寻找资源和示例,但我找到的所有内容都在单个文件中创建了模型。

提前致谢!

fun*_*man 0

让我们看一下full-stack-fastapi-postgresql,这是 FastAPI 作者创建的样板模板:

基础.py

from app.db.base_class import Base 
from app.models.item import Item  
from app.models.user import User
Run Code Online (Sandbox Code Playgroud)

初始化数据库.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:
    ...
Run Code Online (Sandbox Code Playgroud)

因此,正如您所看到的,这是导入模型的一种流行方式,您可以在这里找到更多讨论: https: //github.com/tiangolo/full-stack-fastapi-postgresql/issues/28