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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With