Skip to content

Pydantic dict() method for SQLModel objects does not include relationships #489

@tcompa

Description

@tcompa

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_dict

Below 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

Other possibly related issues:

A possibly related issue:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions