我对 fastAPI 比较陌生。
我正在开发一组API。为了使我的项目结构更好,我将模型分成了多个文件。现在,我有一个员工和技能表。员工与技能之间存在一对多的关系,每个员工可以拥有多种技能,这些技能通过
employee_id
联系在一起。
这是我的主要课程,我使用了路由器:
#main.py
app.include_router(skill.router, prefix="/skill", tags=["skill"])
app.include_router(employee.router, prefix="/employee", tags=["employee"])
#employee.py
Base = declarative_base()
class Employee(Base):
__tablename__ = "core_employees"
employee_id = mapped_column(Integer, primary_key=True, index=True)
first_name = mapped_column(String)
last_name = mapped_column(String)
skills = relationship(Skill)
#skill.py
Base = declarative_base()
class Skill(Base):
__tablename__ = "skills"
skill_id = mapped_column(Integer, primary_key=True, index=True)
employee_id = mapped_column(Integer, ForeignKey(Employee.employee_id))
skill_name = mapped_column(String)
skill_level = mapped_column(Integer)
employee = relationship(Employee)
文件结构是这样的:
main.py
model/
│
├── employee.py
├── skill.py
我最初很难将模型分成不同的文件,例如
employee = relationship('Employee')
不起作用,我必须通过实际的课程。
现在有问题了。
skill.py
必须导入employee.py
,反之亦然,这是一个循环依赖问题。
我尝试将两个导入添加到package(使模型成为一个包),但它对我不起作用。我还尝试了forward refs,但这也不起作用。请帮助我。
谢谢。
您需要对所有相关型号使用一个通用的
Base
。
#main.py
app.include_router(skill.router, prefix="/skill", tags=["skill"])
app.include_router(employee.router, prefix="/employee", tags=["employee"])
#database.py
Base = declarative_base()
#employee.py
from database import Base
class Employee(Base):
__tablename__ = "core_employees"
employee_id = mapped_column(Integer, primary_key=True, index=True)
first_name = mapped_column(String)
last_name = mapped_column(String)
skills = relationship("Skill" )
#skill.py
from database import Base
from employee import Employee
class Skill(Base):
__tablename__ = "skills"
skill_id = mapped_column(Integer, primary_key=True, index=True)
employee_id = mapped_column(Integer, ForeignKey(Employee.employee_id))
skill_name = mapped_column(String)
skill_level = mapped_column(Integer)
employee = relationship(Employee)