Skip to content

Required/NonNull behaviour for Pydantic fields with defaults #48

Closed
@davidkell

Description

@davidkell

We think the following code produces an incorrect schema:

from pydantic import BaseModel
from graphene_pydantic import PydanticObjectType
import graphene

class ExampleModel(BaseModel):
	attr: int = 0

class ExampleType(PydanticObjectType):
	class Meta:
		model = ExampleModel

class Query(graphene.ObjectType):
    example = graphene.Field(ExampleType)

    @staticmethod
    def resolve_example(parent, info):
        # fetch actual PersonModels here
        return [ExampleType()]

schema = graphene.Schema(query=Query)

print(schema)

Result:

schema {
  query: Query
}

type ExampleType {
  attr: Int
}

type Query {
  example: ExampleType
}

AFAICT, the Int field on ExampleType should not be nullable, since there will always be a default value and this value cannot be null. Instead it should be:

type ExampleType {
  attr: Int!
}

I think it's a one line fix here, you need to change:

field_kwargs.setdefault("required", field.required)

to

field_kwargs.setdefault("required", not field.allow_none)

For reference, the Pydantic docs on distinguishing nullability (optional) and required fields.

If you agree with this, I'm happy to submit a PR - we are already doing this on our fork.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions