Skip to content

Commit 68a9fb9

Browse files
committed
Improved Django field choice converter
1 parent bd88f23 commit 68a9fb9

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

graphene/contrib/django/converter.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,26 @@
1+
from collections import Iterable
12
from django.db import models
23

34
from ...core.types.scalars import ID, Boolean, Float, Int, String
45
from ...core.classtypes.enum import Enum
6+
from ...utils import to_const
57
from .compat import RelatedObject, UUIDField
68
from .utils import get_related_model, import_single_dispatch
79

810
singledispatch = import_single_dispatch()
911

1012

13+
def convert_choices(choices):
14+
for value, name in choices:
15+
yield to_const(name), value
16+
17+
1118
def convert_django_field_with_choices(field):
1219
choices = getattr(field, 'choices', None)
1320
if choices:
1421
meta = field.model._meta
1522
name = '{}_{}_{}'.format(meta.app_label, meta.object_name, field.name)
16-
return Enum(name.upper(), choices, description=field.help_text)
23+
return Enum(name.upper(), list(convert_choices(choices)), description=field.help_text)
1724
return convert_django_field(field)
1825

1926

graphene/contrib/django/tests/models.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ class Article(models.Model):
3030
('es', 'Spanish'),
3131
('en', 'English')
3232
], default='es')
33+
importance = models.IntegerField('Importance', null=True, blank=True,
34+
choices=[(1, u'Very important'), (2, u'Not as important')])
3335

3436
def __str__(self): # __unicode__ on Python 2
3537
return self.headline

graphene/contrib/django/tests/test_converter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,8 @@ class Meta:
103103
assert issubclass(graphene_type, graphene.Enum)
104104
assert graphene_type._meta.type_name == 'TEST_TRANSLATEDMODEL_LANGUAGE'
105105
assert graphene_type._meta.description == 'Language'
106-
assert graphene_type.__enum__.__members__['es'].value == 'Spanish'
107-
assert graphene_type.__enum__.__members__['en'].value == 'English'
106+
assert graphene_type.__enum__.__members__['SPANISH'].value == 'es'
107+
assert graphene_type.__enum__.__members__['ENGLISH'].value == 'en'
108108

109109

110110
def test_should_float_convert_float():

0 commit comments

Comments
 (0)