-
Notifications
You must be signed in to change notification settings - Fork 4
Description
While working on #1 with @mfranzon , we hit an unexpected behavior of the .dict() pydantic method when combined with SQLModel objects, where it only exports fields (e.g. workflow.id) and not relationships (e.g. workflow.task_list).
Because of the limited of scope of our needs (we "only" need to transform a Workflow object in a nested python dictionary and to remove the ID attributes, and possibly we'll do something similar for a Project or another model), we will now implement a simple custom solution for #1 on the line of
def export(wf: Workflow) -> dict:
wfread = WorkflowRead(**wf.__dict__)
wfread_dict = wfread.dict(exclude={"id", "project_id"})
for ind, wftask in enumerate(wfread_dict["task_list"]):
wftask.pop("id")
wftask.pop("task_id")
wftask.pop("workflow_id")
wftask["task"].pop("id")
wfread_dict["task_list"][ind] = wftask
return wfread_dictBelow are some relevant references, in case we want/need to improve this in the future:
One possible explanation is that the current behavior is needed to avoid infinite recursion, and the solution is to introduce additional (more explicit, and non-SQLModel-inherited) models. See
- https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/#models-with-relationships
- Add config option to load relationship fields. fastapi/sqlmodel#445 (this open PR also has useful minimal-failing-examples)
Other possibly related issues:
- Selectin for the SQLModels relations fastapi/sqlmodel#444
- Cannot get nested objects when converting to dict fastapi/sqlmodel#347
- JSON Fields for Nested Pydantic Models? fastapi/sqlmodel#63
A possibly related issue: