Skip to content

Commit de424f7

Browse files
committed
Merge pull request #191 from graphql-python/django-choices-grouping
Django choices grouping
2 parents 6eb0008 + 9e715cd commit de424f7

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

graphene/contrib/django/converter.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,20 @@
1515

1616
def convert_choices(choices):
1717
for value, name in choices:
18-
yield to_const(force_text(name)), value
18+
if isinstance(name, (tuple, list)):
19+
for choice in convert_choices(name):
20+
yield choice
21+
else:
22+
yield to_const(force_text(name)), value
1923

2024

2125
def convert_django_field_with_choices(field):
2226
choices = getattr(field, 'choices', None)
23-
model = getattr(field, 'model', None)
24-
if choices and model:
25-
meta = model._meta
27+
if choices:
28+
meta = field.model._meta
2629
name = '{}_{}_{}'.format(meta.app_label, meta.object_name, field.name)
27-
return Enum(name.upper(), list(convert_choices(choices)), description=field.help_text)
30+
graphql_choices = list(convert_choices(choices))
31+
return Enum(name.upper(), graphql_choices, description=field.help_text)
2832
return convert_django_field(field)
2933

3034

graphene/contrib/django/tests/test_converter.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,23 @@ class Meta:
118118
assert graphene_type.__enum__.__members__['ENGLISH'].value == 'en'
119119

120120

121+
def test_field_with_grouped_choices():
122+
field = models.CharField(help_text='Language', choices=(
123+
('Europe', (
124+
('es', 'Spanish'),
125+
('en', 'English'),
126+
)),
127+
))
128+
129+
class GroupedChoicesModel(models.Model):
130+
language = field
131+
132+
class Meta:
133+
app_label = 'test'
134+
135+
convert_django_field_with_choices(field)
136+
137+
121138
def test_field_with_choices_gettext():
122139
field = models.CharField(help_text='Language', choices=(
123140
('es', _('Spanish')),

0 commit comments

Comments
 (0)