Skip to content

Commit 8c20e18

Browse files
committed
Add schema test
1 parent b4b64fd commit 8c20e18

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

graphene_django/converter.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,13 @@ def generate_enum_name(django_model_meta, field):
8181
return name
8282

8383

84+
def convert_choice_field_to_enum(field, name=None):
85+
if name is None:
86+
name = generate_enum_name(field.model._meta, field)
87+
choices = field.choices
88+
return convert_choices_to_named_enum_with_descriptions(name, choices)
89+
90+
8491
def convert_django_field_with_choices(
8592
field, registry=None, convert_choices_to_enum=True
8693
):
@@ -90,8 +97,7 @@ def convert_django_field_with_choices(
9097
return converted
9198
choices = getattr(field, "choices", None)
9299
if choices and convert_choices_to_enum:
93-
name = generate_enum_name(field.model._meta, field)
94-
enum = convert_choices_to_named_enum_with_descriptions(name, choices)
100+
enum = convert_choice_field_to_enum(field)
95101
required = not (field.blank or field.null)
96102
converted = enum(description=field.help_text, required=required)
97103
else:

graphene_django/tests/test_types.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from .. import registry
1212
from ..settings import graphene_settings
1313
from ..types import DjangoObjectType, DjangoObjectTypeOptions
14+
from ..converter import convert_choice_field_to_enum
1415
from .models import Article as ArticleModel
1516
from .models import Reporter as ReporterModel
1617

@@ -529,3 +530,43 @@ class Query(ObjectType):
529530
"""
530531
)
531532
graphene_settings.CHOICES_TO_ENUM_UNIQUE_TYPE_NAME = False
533+
534+
def test_django_objecttype_choices_override_enum(self, PetModel):
535+
def convert_choice(model, field_name, **kwargs):
536+
return convert_choice_field_to_enum(
537+
model._meta.get_field(field_name), **kwargs
538+
)
539+
540+
class PetModelKind(DjangoObjectType):
541+
kind = Field(convert_choice(PetModel, "kind", name="CustomEnumName"))
542+
543+
class Meta:
544+
model = PetModel
545+
fields = ["id", "kind"]
546+
547+
class Query(ObjectType):
548+
pet = Field(PetModelKind)
549+
550+
schema = Schema(query=Query)
551+
552+
assert str(schema) == dedent(
553+
"""\
554+
schema {
555+
query: Query
556+
}
557+
558+
enum DjangoModelTestsPetModelKindChoices {
559+
CAT
560+
DOG
561+
}
562+
563+
type PetModelKind {
564+
id: ID!
565+
kind: DjangoModelTestsPetModelKindChoices!
566+
}
567+
568+
type Query {
569+
pet: PetModelKind
570+
}
571+
"""
572+
)

0 commit comments

Comments
 (0)