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)
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too