Added descriptions to Django choices enum conversion. Fixed #279

This commit is contained in:
Syrus Akbary 2016-09-11 16:08:35 -07:00
parent 2ae6cc3b7c
commit a2140110c2
2 changed files with 23 additions and 7 deletions

View File

@ -15,13 +15,19 @@ from .fields import get_connection_field
singledispatch = import_single_dispatch() singledispatch = import_single_dispatch()
def convert_choices(choices): def convert_choice_name(name):
for value, name in choices: return to_const(force_text(name))
if isinstance(name, (tuple, list)):
for choice in convert_choices(name):
def get_choices(choices):
for value, help_text in choices:
if isinstance(help_text, (tuple, list)):
for choice in get_choices(help_text):
yield choice yield choice
else: else:
yield to_const(force_text(name)), value name = convert_choice_name(help_text)
description = help_text
yield name, value, description
def convert_django_field_with_choices(field, registry=None): def convert_django_field_with_choices(field, registry=None):
@ -29,8 +35,16 @@ def convert_django_field_with_choices(field, registry=None):
if choices: if choices:
meta = field.model._meta meta = field.model._meta
name = '{}{}'.format(meta.object_name, field.name.capitalize()) name = '{}{}'.format(meta.object_name, field.name.capitalize())
graphql_choices = list(convert_choices(choices)) choices = list(get_choices(choices))
enum = Enum(name, list(graphql_choices)) named_choices = [(c[0], c[1]) for c in choices]
named_choices_descriptions = {c[0]:c[2] for c in choices}
class EnumWithDescriptionsType(object):
@property
def description(self):
return named_choices_descriptions[self.name]
enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType)
return enum(description=field.help_text) return enum(description=field.help_text)
return convert_django_field(field, registry) return convert_django_field(field, registry)

View File

@ -117,7 +117,9 @@ def test_field_with_choices_convert_enum():
assert isinstance(graphene_type, graphene.Enum) assert isinstance(graphene_type, graphene.Enum)
assert graphene_type._meta.name == 'TranslatedModelLanguage' assert graphene_type._meta.name == 'TranslatedModelLanguage'
assert graphene_type._meta.enum.__members__['SPANISH'].value == 'es' assert graphene_type._meta.enum.__members__['SPANISH'].value == 'es'
assert graphene_type._meta.enum.__members__['SPANISH'].description == 'Spanish'
assert graphene_type._meta.enum.__members__['ENGLISH'].value == 'en' assert graphene_type._meta.enum.__members__['ENGLISH'].value == 'en'
assert graphene_type._meta.enum.__members__['ENGLISH'].description == 'English'
def test_field_with_grouped_choices(): def test_field_with_grouped_choices():