我有两个模型,Company
和Employee
,以多对一的关系。它们在不同的Flask蓝图中定义。我正在尝试添加级联,这使我需要在Company
上定义关系(而不仅仅是Employee
上设置了backref
的关系。
company_blueprint / models.py:
class Company(Base):
id = Column(Integer, primary_key=True)
employees = relationship("Employee", back_populates="company", cascade="all")
employee_blueprint / models.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
中导入Employee,但后来我遇到了循环导入问题。
我该如何解决这个问题?
修改:感谢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.
这仍然感觉有点尴尬。
答案 0 :(得分:0)
我在大多数模型类中使用这种关系。根据我的理解,你不需要在这两个类中有任何特殊的东西或关系。只需在父模型类中添加一个关系并添加backref
即可。
class Company(Base):
id = Column(Integer, primary_key=True)
employees = relationship("Employee", backref="company", cascade="all, delete-orphan")