【问题标题】:FastAPI SQLAlchemy relationship models loadingFastAPI SQLAlchemy 关系模型加载
【发布时间】:2023-03-18 01:40:01
【问题描述】:

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

帐号:

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

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

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


def init_db():
    import_all()

我的问题是,有没有更聪明的方法以正确的顺序加载模型?因为现在我只有两个模型,但很快它可以增长到几十个模型,我认为这将成为一个管理的怪物。 我查找了资源和示例,但我发现的所有内容都在单个文件中创建了模型。

提前致谢!

【问题讨论】:

    标签: python sqlalchemy fastapi


    【解决方案1】:

    我们看一下full-stack-fastapi-postgresql,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:
        ...
    

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

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2019-10-02
      • 2016-04-25
      • 2015-02-28
      相关资源
      最近更新 更多