Skip to content

Support discriminated union #356

Closed
Closed
@wholmen

Description

@wholmen

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Literal, Union, Optional
from sqlmodel import SQLModel, Field


class Bar(SQLModel):
    class_type: Literal["bar"] = "bar"
    name: str


class Foo(SQLModel):
    class_type: Literal["foo"] = "foo"
    name: str
    id: Optional[int]


class FooBar(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    data: Union[Foo, Bar] = Field(discriminator="class_type")

Description

  • No support for Pydantic 1.9's implementation of discriminated union

Wanted Solution

Would like to have support for discriminated union in SQLModel-classes

Wanted Code

from typing import Literal, Union, Optional
from sqlmodel import SQLModel, Field


class Bar(SQLModel):
    class_type: Literal["bar"] = "bar"
    name: str


class Foo(SQLModel):
    class_type: Literal["foo"] = "foo"
    name: str
    id: Optional[int]


class FooBar(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    data: Union[Foo, Bar] = Field(discriminator="class_type")

Alternatives

No response

Operating System

Linux

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.10.4

Additional Context

Pydantic has added support for discrimated unions, something I use in my project with Pydantic + SQLAlchemy.

I want to switch to SQLModel, but cannot switch before discriminated unions

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions