Search code examples
pythondjangographqlgraphene-django

Django-Graphene: On a model ChoiceField, graphene expects a Type but got a value


On Django-Graphene, I have this model:

class Entry(models.Model):
    STATE_CHOICES = [
        ("Open", "Open"),
        ("Processing", "Processing"),
        ("Closed", "Closed"),
        ("Deleted", "Deleted"),
    ]

    # ...
    state = models.CharField(max_length=10, choices=STATE_CHOICES,
                             default="Open")

With the following Graphene schema:

class EntryType(DjangoObjectType):
    class Meta:
        model = models.Entry

class Query(graphene.ObjectType):
    entries = graphene.List(EntryType)

    def resolve_entries(self, info):
        return models.Entry.objects.all()

But when I use the next query:

query AllEntries{
  entries{
    id
    state
  }
}

I get this error:

{
  "errors": [
    {
      "message": "Expected a value of type \"EntryState\" but received: OPEN",
      "path": [
        "entries",
        1,
        "state"
      ]
    }
  ],
}

Can someone explain me what I'm doing wrong ?


Solution

  • This is because of this line:

    state = models.CharField(max_length=10, choices=STATE_CHOICES, default="Open")
    

    Even though this is accepted by the ORM and is saved correctly in the database, it confuses graphene because it's trying to compare a string with an enum value.

    To remedy this, you can do it like this:

    state = models.CharField(max_length=10, choices=STATE_CHOICES, default=STATE_CHOICES.Open)
    

    If you do not want to create/do migration, you can alternatively create a graphene ENUM type then map it inside your resolve_state function.