Maybe Field Error
Description
This error is thrown when a field of a @strawberry.pydantic.input uses
strawberry.Maybe in a way the integration doesnβt support:
- with a default other than
None, or a default factory; - with Pydantic metadata outside the
Maybe, likeAnnotated[strawberry.Maybe[int], Field(ge=0)]orstrawberry.Maybe[int] = Field(None, ge=0): Pydantic would apply the constraints to thestrawberry.Some, not to the value in it; - with an
afterorplain@field_validatornaming the field: anaftervalidator would get thestrawberry.Some, and aplainone would replace the validation of theMaybe; - with an explicit
Nonedefault that Pydantic validates, because ofvalidate_default.
A Maybe field on a @strawberry.pydantic.type or
@strawberry.pydantic.interface raises a
MaybeFieldOnOutputTypeError instead, as
Maybe is for inputs.
For example, the following code throws this error:
import pydanticimport strawberry
@strawberry.pydantic.inputclass UpdateUserInput(pydantic.BaseModel): name: strawberry.Maybe[str] = "Ada" How to fix this error
Remove the default: a Maybe field is None when the client leaves it out, and
a strawberry.Some with the value when it sends one. Pydantic validates the
value inside the Some , and doesnβt validate the None the field gets when
itβs left out.
import pydanticimport strawberry
@strawberry.pydantic.inputclass UpdateUserInput(pydantic.BaseModel): name: strawberry.Maybe[str]
@strawberry.typeclass Mutation: @strawberry.mutation def update_user(self, input: UpdateUserInput) -> str: if input.name is None: return "Name was omitted"
return f"Name was supplied: {input.name.value!r}" Put constraints and validators in the type inside the Maybe , where they apply
to the value. A @field_validator with mode="before" or mode="wrap" works
too, as it gets the value the client sent:
from typing import Annotated
import pydanticimport strawberry
def check_name(name: str) -> str: return name.strip()
@strawberry.pydantic.inputclass UpdateUserInput(pydantic.BaseModel): age: strawberry.Maybe[Annotated[int, pydantic.Field(ge=0)]] name: strawberry.Maybe[Annotated[str, pydantic.AfterValidator(check_name)]]