Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add options to override how Django Choice fields are converted to Enums #860

Merged
merged 12 commits into from
Mar 13, 2020
Prev Previous commit
Next Next commit
Add schema test
  • Loading branch information
jkimbo committed Feb 23, 2020
commit 8c20e183ad2d880aaba5b35ce9d6d1374e575d12
10 changes: 8 additions & 2 deletions graphene_django/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
):
Expand All @@ -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:
Expand Down
41 changes: 41 additions & 0 deletions graphene_django/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
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

Expand Down Expand Up @@ -529,3 +530,43 @@ class Query(ObjectType):
"""
)
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
}
"""
)