【问题标题】:FastApi/Pydantic access many to one relationship from parent tableFastApi/Pydantic 从父表访问多对一关系
【发布时间】:2020-11-17 01:36:04
【问题描述】:

我有这样的结构:

SqlAlchemy 模型

class MPrueba(Base):

    __tablename__ = 'M_pruebas'

    idpruebas = Column(Integer, primary_key=True)
    idfuentes = Column(ForeignKey('M_fuentes.idfuentes', ondelete='RESTRICT', onupdate='RESTRICT'), index=True)

    M_fuente = relationship('MFuente')


class MRegla(Base):

    __tablename__ = 'M_reglas'

    idreglas = Column(Integer, primary_key=True)
    idpruebas = Column(ForeignKey('M_pruebas.idpruebas', ondelete='RESTRICT', onupdate='RESTRICT'), index=True)
    nombre = Column(String(40))

    M_prueba = relationship('MPrueba') 

如您所见,MRegla 类上存在指向 MPrueba 类的关系。这意味着当我在 MRegla 类上发出一些获取请求时,M_prueba 字段应该包含来自 MPrueba 类的数据。如何从 MPrueba 类访问该关系?我想生成一个像这样的 pydantic 模型:

MPrueba 类的 pydantic 架构

class Prueba(BaseModel): 
    idpruebas: int
    idfuentes: int
    reglas : # Append the MRegla here

    class Config:
        orm_mode = True

感谢您的帮助。

【问题讨论】:

  • 我不明白你在这里附加 MRegla 是什么意思。
  • 如果您找到答案,请写下您的解决方案。

标签: python api sqlalchemy fastapi pydantic


【解决方案1】:

如果我理解正确的话,我正在处理类似的问题。虽然我不确定你是否有多对一的关系,但无论如何。

使用您之前定义的 Pydantic 模型:

class MRegla(BaseModel):
    ...

class Prueba(BaseModel): 
    idpruebas: int
    idfuentes: int
    reglas : MRegla

    class Config:
        orm_mode = True

如果您需要 MRegla 模型的一个子集,请定义一个包含必填字段的附加 Pydantic 模型并使用它。

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 2021-09-24
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多