Skip to content

From_pydantic fails on union type #3641

@tobiasBora

Description

@tobiasBora

Describe the Bug

If I do:

QuestionType = Annotated[Union[QuestionMultipleChoiceType, QuestionTextType, QuestionNumberType],
                         strawberry.union("Question")]

Then I'm not able to call:

QuestionType.from_pydantic(question)

as from_pydantic does not exist on union types.

MWE:

import strawberry
import operator
from pydantic import BaseModel, TypeAdapter
from typing import Union, Literal, Annotated
from strawberry.schema.config import StrawberryConfig

# Pedantic classes
class QuestionMultipleChoice(BaseModel):
    # This helps pydantic to distinguish the types
    kind: str = "QuestionMultipleChoice"
    nbChoices: int

class QuestionText(BaseModel):
    kind: str = "QuestionText"
    
class QuestionNumber(BaseModel):
    kind: str = "QuestionNumber"

Question = Union[
    QuestionMultipleChoice,
    QuestionText,
    QuestionNumber
]

# GraphQL types

@strawberry.experimental.pydantic.type(model=QuestionMultipleChoice, all_fields=True)
class QuestionMultipleChoiceType:
    pass

@strawberry.experimental.pydantic.type(model=QuestionText, all_fields=True)
class QuestionTextType:
    pass

@strawberry.experimental.pydantic.type(model=QuestionNumber, all_fields=True)
class QuestionNumberType:
    pass

# Redefining all types in the union seems very verbose and error-prone. Is this really the good approach?
QuestionType = Annotated[Union[QuestionMultipleChoiceType, QuestionTextType, QuestionNumberType],
                         strawberry.union("Question")]

# Fake a redis database

data = {
    "questionA": QuestionMultipleChoice(nbChoices=4).model_dump_json(),
    "questionB": QuestionText().model_dump_json(),
    "questionC": QuestionNumber().model_dump_json(),
}
print(data)

@strawberry.type
class Query:
    @strawberry.field
    def get_ident(self, questionID: str) -> QuestionType:
        question = TypeAdapter(Question).validate_json(data[questionID])
        print("question:", question)
        return QuestionType.from_pydantic(question)

config = StrawberryConfig(
    default_resolver=operator.getitem
)

schema = strawberry.Schema(query=Query, config=config)

System Information

  • Operating system: NixOs
  • Strawberry version (if applicable): 0.237.3

Additional Context

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions