I have been trying to get fastAPI to return recursive family tree without any success.
class DBPerson(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String, index=True)
...
father_id = Column(Integer, ForeignKey("person.id"), nullable=True)
father = relationship("DBPerson", back_populates="children")
mother_id = Column(Integer, ForeignKey("person.id"), nullable=True)
mother = relationship("DBPerson", back_populates="children")
children = relationship("DBPerson", back_populates=???)
And to create a family tree, I want both father and mother to return their father and mother...
class PersonBase(BaseModel):
name: str
id: int
father: PersonBase | None = None
mother: PersonBase | None = None
class PersonMinimal(PersonBase):
class Config:
orm_mode = True
Though doing it like this returns an error inside the PersonBase class with father and mother as the PersonBase class has not been defined yet.
I have seen examples of this where you have a "parent", but that does not tell me whether I have the mother or father, unless the object in the list would also return the gender... but I would rather do it this way if possible. Any help appreciated.
Also, if anyone knows a way to limit how many generations the recursive will go, that would also be appreciated.
I would be expecting the api to return the following:
{
id: int
name: str
father: {
id: int
name: str
father: { ... }
mother: { ... }
}
mother: {
id: int
name: str
father: { ... }
mother: { ... }
}
}