Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a single enum for django model and graphql mutation arguments?

I've defined Django models with fields containing text choices corresponding to enums. The GraphQL API provides mutations (which are not derived from models directly) with arguments of type enum which shall accept the same values as the models only. How can I get rid of my dublication?

models.py:

class SomeModel(models.Model):

    class SomeEnum(models.TextChoices):

        A = "A", _("Option A")
        B = "B", _("Option B")

    enum_field = models.CharField(
        max_length=1,
        choices=SomeEnum.choices,
        default=SomeEnum.A,
    )

schema.py:


class SomeEnumSchema(graphene.Enum):

    A = "A"
    B = "B"


class SomeMutation(graphene.Mutation):

    class Arguments:
        some_enum = SomeEnumSchema(required=True)

like image 969
thinwybk Avatar asked Mar 02 '23 14:03

thinwybk


1 Answers

You can use graphene.Enum.from_enum().

This function can convert normal Enum type to graphene.Enum.

Do notice that models.TextChoices is only available for Dajango version above 3.0

models.py (for Django version >= 3.0)

from django.db import models

class SomeModel(models.Model):

    class SomeEnum(models.TextChoices):

        A = "A", _("Option A")
        B = "B", _("Option B")

    enum_field = models.CharField(
        max_length=1,
        choices=SomeEnum.choices,
        default=SomeEnum.A,
    )

models.py (for Django version < 3.0)

from enum import Enum
class SomeEnum(Enum):
    A = "A"
    B = "B"

schema.py:

SomeEnumSchema = graphene.Enum.from_enum(SomeEnum)
class SomeMutation(graphene.Mutation):
    class Arguments:
        some_enum = SomeEnumSchema(required=True)
like image 144
Kant Chen Avatar answered Mar 05 '23 16:03

Kant Chen