QuestionType = Annotated[Union[QuestionMultipleChoiceType, QuestionTextType, QuestionNumberType],
strawberry.union("Question")]
QuestionType.from_pydantic(question)
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)
Describe the Bug
If I do:
Then I'm not able to call:
as
from_pydanticdoes not exist on union types.MWE:
System Information
Additional Context