strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.01k stars 533 forks source link

Add Support for Pydantic Discriminated Union #2317

Open wholmen opened 2 years ago

wholmen commented 2 years ago

Since Pydantic 1.9, pydantic has supported the use of discriminated unions as a way to force what union type Pydantic evaluates an object by. Pydantic models with discriminated unions raise an error, at least because the typing.Literal is not supported

Feature Request Type

Description

The following code will raise the error when it's converted to a GraphQL model: TypeError: fields cannot be resolved. Unexpected type 'typing.Literal"

class Foo(BaseModel):
    class_type: Literal["foo"] = "foo"
    foo: str

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

class Model(BaseModel):
    foobar: Union[Foo, Bar] = Field(discriminator="class_type")

The point of this, is to tell pydantic explicitly if the foobar variable should be parsed as a Bar object or a Foo object. The default behavior without discriminated unions is to try Foo first, which will always succeed in this case.

Upvote & Fund

Fund with Polar

huyz commented 1 year ago

I'm also running into this when generating Pydantic models using https://github.com/jhnnsrs/turms