FastAPI - Pydantic and SQLAlchemy nested models validation error

Viewed 342

I am having some problems trying to retrieve information from 2 models.

models.py

class MachineGroups(Base):
    __tablename__ = 'MachineGroups'

    MachineGroupsId = Column(NVARCHAR(25), primary_key=True)
    Description = Column(NVARCHAR(255))

    machines = relationship("Machines")


class Machines(Base):
    __tablename__ = 'Machines'

    MachinesId = Column(NVARCHAR(50), primary_key=True)
    Description = Column(NVARCHAR(255))
    MachineGroupsId = Column(NVARCHAR(25), ForeignKey("MachineGroups.MachineGroupsId", ondelete="SET NULL"), nullable=True)

schemas.py

class MachineGroups(BaseModel):
    MachineGroupsId: str
    Description: str

    class Config:
        orm_mode = True


class Machines(BaseModel):
    MachinesId: str
    Description: str
    MachineGroupsId: Optional[MachineGroups] = None

    class Config:
        orm_mode = True

When I try to query the Machines table I get the error:

pydantic.error_wrappers.ValidationError: 1 validation error for Machines
response -> 0 -> MachineGroupsId-> MachineGroupsId
  field required (type=value_error.missing)

I think the relationship is set up correctly, but I don't understand where the problem is.

What am I doing wrong?

Thank you.

0 Answers
Related