我有两个模型,Company
和Employee
,处于多对一关系中。它们在不同的 Flask 蓝图中定义。我正在尝试添加一个级联,这使得我需要在Company
上定义一个关系(而不仅仅是一个Employee
与backref
集合的关系)。
company_blueprint/型号.py:
class Company(Base):
id = Column(Integer, primary_key=True)
employees = relationship("Employee", back_populates="company", cascade="all")
employee_blueprint/型号.py:
from app.company_blueprint.models import Company
class Employee(Base):
name = Column(String)
company_id = Column(ForeignKey(Company.id))
company = relationship("company", back_populates="employees")
问题是,当我尝试删除company_blueprint/views.py
中的公司时,Employee
模型未加载。我得到:
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Company|company, expression 'Employee' failed to locate a name ("name 'Employee' is not defined"). If this is a class name, consider adding this relationship() to the <class 'app.company_model.models.Company'> class after both dependent classes have been defined.
我可以尝试在company_blueprint.models
中导入员工,但随后我遇到了循环导入问题。
我该如何解决这个问题?
编辑:感谢Paradoxis,现在我已经确定了以下内容:
- 使用字符串引用外键列,例如
company_id = Column(ForeignKey("company.id"))
- 在我的
app.py
,首先导入所有模型,然后进行其他任何操作,即
-
import flask
import app.employee_blueprint.models
import app.company_blueprint.models
# import other views, modules, etc.
这还是感觉有点尴尬。
我在大多数模型类中使用了这种关系。根据我的理解,在这两个班级中,你不需要任何特殊的东西或关系。只需在父模型类中添加关系并添加一个backref
,它就可以工作。
class Company(Base):
id = Column(Integer, primary_key=True)
employees = relationship("Employee", backref="company", cascade="all, delete-orphan")