Skip to content

DjangoObjectType Generates Wrong Schema on Arrayfield #536

Closed
@helloqiu

Description

@helloqiu

Description

Get wrong result for python manage.py graphql_schema.
Here's an example repo which can make it more clear:
https://github.com/helloqiu/graphene_bug_example

If I define the model as followed:

from django.db import models
from django.contrib.postgres.fields import ArrayField


class Example(models.Model):
    simple_array = ArrayField(models.CharField(max_length=255))

and write the schema like this:

from graphene_django import DjangoObjectType
import graphene

from graphene_bug_example.models import Example as ExampleModel


class Example(DjangoObjectType):
    required_field = graphene.String(required=True)

    class Meta:
        model = ExampleModel


class Query(graphene.ObjectType):
    examples = graphene.List(Example)

schema = graphene.Schema(query=Query)

then run python manage.py graphql_schema, the String in simpleArray, which is an ArrayField, is nullable:

...
            {
              "name": "simpleArray",
              "description": "",
              "args": [],
              "type": {
                "kind": "NON_NULL",
                "name": null,
                "ofType": {
                  "kind": "LIST",
                  "name": null,
                  "ofType": {
                    "kind": "SCALAR",
                    "name": "String",
                    "ofType": null
                  }
                }
              },
              "isDeprecated": false,
              "deprecationReason": null
            },
...

Possible Solution

@convert_django_field.register(ArrayField)
def convert_postgres_array_to_list(field, registry=None):
    base_type = convert_django_field(field.base_field)
    if not isinstance(base_type, (List, NonNull)):
        base_type = type(base_type)
    return List(base_type, description=field.help_text, required=not field.null)

https://github.com/graphql-python/graphene-django/blob/master/graphene_django/converter.py#L212
I think we should restore required parameter after base_type = type(base_type).
Something like this:

...
    if not isinstance(base_type, (List, NonNull)):
        base_type = type(base_type) if not base_type.kwargs['required'] else NonNull(type(base_type))
...

Maybe I will create a PR if this is verified as a bug by the maintainer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions