Skip to content Skip to sidebar Skip to footer

Returning A List Of Enums With String Values With Graphene

This is using Python and the Graphene library. I want to provide a list of constants to my front-end via GraphQL. I went down the route of using inspection, but it will only output

Solution 1:

I don't think you add or remove fields from the enumValues since it is the standard.

But, you can add the description by specifying a descriptionproperty in the enum class.

import graphene

from enum import Enum as PyEnum


classFruitEnum(PyEnum):
    APPLE = "Apple"
    BANANA = "Banana"
    ORANGE = "Orange"defget_field_description(self):
        mapper = {
            "default": "default description",
            "APPLE": "Apple description"
        }
        return mapper.get(self.name, mapper['default'])

    @propertydefdescription(self):
        return self.get_field_description()


classFruitType(graphene.ObjectType):
    foo = graphene.Enum.from_enum(FruitEnum)()

Thus you will get a response as,

{"data":{"__type":{"name":"FruitEnum","enumValues":[{"name":"APPLE","description":"Apple description"},{"name":"BANANA","description":"default description"},{"name":"ORANGE","description":"default description"}]}}}

Solution 2:

Using Django you can simply write:

from django.db import models

from django.utils.translation import gettext_lazy as _   # Provides a convenient way to translate your descriptionsclassFruitEnum(models.TextChoices):
    APPLE = "Apple", _('Apple description goes here')
    BANANA = "Banana", _('Banana description goes here')
    ORANGE = "Orange", _('Orange description goes here')

Thus you will get a response as,

{"data":{"__type":{"name":"FruitEnum","enumValues":[{"name":"APPLE","description":"Apple description goes here"},{"name":"BANANA","description":"Banana description goes here"},{"name":"ORANGE","description":"Orange description goes here"}]}}}

Post a Comment for "Returning A List Of Enums With String Values With Graphene"