Skip to content

How to create a field to expose Model Fields' choices #471

Description

@ZuluPro

I have a model field with choices:

CHOICES = [
  ('foo', 'Foo'),
  ('bar', 'Bar'),
]

class MyModel(models.Model):
    ham = models.CharField(max_length=2, choices=CHOICES)

So, in the schema I have the model and its choices. But can I expose the choices ?
I tried this but without success:

MyModelHamType = registry.get_converted_field(models.MyModel._meta.get_field('ham')).get_type()

class Query(object):
    choices = graphene.Field(MyModelHamType)

    def resolve_choices(self, info, **kwargs):
        # What to do here
        return MyModelHamType

The code above gives the following thing:
Request :

query {
  hams
}

Response:

{
  "errors": [
    {
      "message": "Expected a value of type \"MyModelHam\" but received: MyModelHam",
      "path": [
        "hams"
      ]
    }
  ],
  "data": {
    "hams": null
  }
}

It seems that as the object aren't the of the same type (Pythonicly saying), Graphene doesn't want to handle.


I could recreate myself a MyModelHamType with Enum, but it will be duplicate with the existing one autocreated and already in schema.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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