Master Yoda
Master Yoda

Reputation: 589

FastApi/Pydantic access many to one relationship from parent table

I have a structure like this:

SqlAlchemy models

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') 

As you can see there is a relationship on MRegla class that points to MPrueba class. This mean that when I make some get request on MRegla class, M_prueba field should contain data from MPrueba class. How can I access that relationship from the MPrueba Class ??. I want to generate a pydantic model like this:

pydantic schema for MPrueba class

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

    class Config:
        orm_mode = True

Thanks for your help.

Upvotes: 5

Views: 7633

Answers (1)

bajaco
bajaco

Reputation: 980

I'm dealing with a similar problem, if I'm understanding correctly. Though I'm not sure that you have a many to one relationship, but regardless.

Use your previously defined Pydantic model:

class MRegla(BaseModel):
    ...

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

    class Config:
        orm_mode = True

If you need a subset of the MRegla model define an additional Pydantic model with the required fields and use that instead.

Upvotes: 1

Related Questions