FastAPI模型错误一对多关系

FastAPI Model error one to many relationship

我是 fastapi 的新手,在建立一对多关系时遇到了一些问题。当我将关系的代码注释掉时,我的 API 工作正常,但是当尝试在其中建立关系时会导致错误提示

reverse_property 'process' 关系 ProcessModel.tasks 引用关系 TaskModel.process,它不引用映射器映射 class ProcessModel->processes

我不确定这意味着什么,我试着四处寻找,但找不到任何相关信息。我已经按照 fastapi 网站上的基本模型创建教程进行操作,这就是我构建以下内容的方式,但仍然出现错误。任何指针将不胜感激。

from sqlalchemy import Column, ForeignKey, Integer, String, DateTime
from sqlalchemy.orm import relationship

from database import Base

class ClientModel(Base):
    __tablename__ = "clients"

    id = Column(Integer, primary_key=True, index=True)
    client_name = Column(String, index=True)

    tasks = relationship("TaskModel", back_populates="client")


class ProcessModel(Base):
    __tablename__ = "processes"

    id = Column(Integer, primary_key=True, index=True)
    process_name = Column(String, index=True)

    tasks = relationship("TaskModel", back_populates="process")


class StatusModel(Base):
    __tablename__ = "statuses"

    id = Column(Integer, primary_key=True, index=True)
    status_name = Column(String, index=True)

    tasks = relationship("TaskModel", back_populates="status")


class TaskModel(Base):
    __tablename__ = "tasks"

    id = Column(Integer, primary_key=True, index=True)
    script_log = Column(String, index=True)
    start_timestamp = Column(DateTime, index=True)
    finish_timestamp = Column(DateTime, index=True)

    client_id = Column(Integer, ForeignKey("clients.id"))
    client = relationship("ClientModel", back_populates="tasks")

    process_id = Column(Integer, ForeignKey("processes.id"))
    process = relationship("ClientModel", back_populates="tasks")

    status_id = Column(Integer, ForeignKey("statuses.id"))
    status = relationship("ClientModel", back_populates="tasks")

添加关系时,第一个参数是包含与该关系的对象 table:

class ProcessModel(Base):
    ...

    tasks = relationship("TaskModel", back_populates="process")

这需要匹配 TaskModel 关系中给出的 class 名称,该关系指向 ProcessModel class:

process_id = Column(Integer, ForeignKey("processes.id"))
process = relationship("ClientModel", back_populates="tasks")
                        ^---- This needs to be ProcessModel

.. 因为那是我们期望定义关系的地方。

process = relationship("ProcessModel", back_populates="tasks")

您必须在其他两个位置进行相同的更改,您仍然在 relationship 调用其他模型时提到 ClientModel