I've got a Python 3.10.8 FastAPI application using SQLModel and having trouble with many-to-many relationships. I can define them okay using strings to refer to the class on the other side of the many. Here is a simplified sample of one side of the many-to-many schema/model:
schedule.py file
class Schedule(ScheduleBase, table=True):
__tablename__ = "schedules"
id: Optional[int] = Field(default=None, primary_key=True)
plans: List["Plan"] = Relationship(back_populates="schedules", link_model=SchedulePlanLink)
Here's the other side of the many-to-many schema/model:
class Plan(PlanBase, table=True):
__tablename__ = "plans"
id: Optional[int] = Field(default=None, primary_key=True)
schedules: List["Schedule"] = Relationship(back_populates="plans", link_model=SchedulePlanLink)
And here's the association table between them:
class SchedulePlanLink(SchedulePlanLinkBase, table=True):
__tablename__ = "schedule_plan_links"
schedule_id: Optional[int] = Field(
default=None, primary_key=True, foreign_key="schedules.id"
)
plan_id: Optional[int] = Field(
default=None, primary_key=True, foreign_key="plans.id"
)
This works and creates the expected tables and FK's, etc. The problem arises when I try to access the data. I have a SQLModel class that looks like this:
class ScheduleReadWithPlans(ScheduleRead):
plans: Optional[List["PlanRead"]] = []
And I have to have this in order to read the data and return it via a route:
ScheduleReadWithPlans.update_forward_refs()
And I can get the schedule data with the list of plans. But if I try the same thing with plan data trying to get a list of schedules (with the appropriate classes define), I end up getting circular references.
Any ideas about how to define/configure this kind of thing to to work?