【发布时间】: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