diff --git a/graphene_django/converter.py b/graphene_django/converter.py index f3b0fd2..e3890ac 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -81,6 +81,13 @@ def generate_enum_name(django_model_meta, field): return name +def convert_choice_field_to_enum(field, name=None): + if name is None: + name = generate_enum_name(field.model._meta, field) + choices = field.choices + return convert_choices_to_named_enum_with_descriptions(name, choices) + + def convert_django_field_with_choices( field, registry=None, convert_choices_to_enum=True ): @@ -90,8 +97,7 @@ def convert_django_field_with_choices( return converted choices = getattr(field, "choices", None) if choices and convert_choices_to_enum: - name = generate_enum_name(field.model._meta, field) - enum = convert_choices_to_named_enum_with_descriptions(name, choices) + enum = convert_choice_field_to_enum(field) required = not (field.blank or field.null) converted = enum(description=field.help_text, required=required) else: diff --git a/graphene_django/tests/test_types.py b/graphene_django/tests/test_types.py index 7a37086..712626d 100644 --- a/graphene_django/tests/test_types.py +++ b/graphene_django/tests/test_types.py @@ -11,6 +11,7 @@ from graphene.relay import Node from .. import registry from ..settings import graphene_settings from ..types import DjangoObjectType, DjangoObjectTypeOptions +from ..converter import convert_choice_field_to_enum from .models import Article as ArticleModel from .models import Reporter as ReporterModel @@ -529,3 +530,43 @@ class TestDjangoObjectType: """ ) graphene_settings.CHOICES_TO_ENUM_UNIQUE_TYPE_NAME = False + + def test_django_objecttype_choices_override_enum(self, PetModel): + def convert_choice(model, field_name, **kwargs): + return convert_choice_field_to_enum( + model._meta.get_field(field_name), **kwargs + ) + + class PetModelKind(DjangoObjectType): + kind = Field(convert_choice(PetModel, "kind", name="CustomEnumName")) + + class Meta: + model = PetModel + fields = ["id", "kind"] + + class Query(ObjectType): + pet = Field(PetModelKind) + + schema = Schema(query=Query) + + assert str(schema) == dedent( + """\ + schema { + query: Query + } + + enum DjangoModelTestsPetModelKindChoices { + CAT + DOG + } + + type PetModelKind { + id: ID! + kind: DjangoModelTestsPetModelKindChoices! + } + + type Query { + pet: PetModelKind + } + """ + )