Skip to content

Commit

Permalink
Improved Django field choice converter
Browse files Browse the repository at this point in the history
  • Loading branch information
syrusakbary committed Apr 2, 2016
1 parent bd88f23 commit 68a9fb9
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
9 changes: 8 additions & 1 deletion graphene/contrib/django/converter.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
from collections import Iterable
from django.db import models

from ...core.types.scalars import ID, Boolean, Float, Int, String
from ...core.classtypes.enum import Enum
from ...utils import to_const
from .compat import RelatedObject, UUIDField
from .utils import get_related_model, import_single_dispatch

singledispatch = import_single_dispatch()


def convert_choices(choices):
for value, name in choices:
yield to_const(name), value


def convert_django_field_with_choices(field):
choices = getattr(field, 'choices', None)
if choices:
meta = field.model._meta
name = '{}_{}_{}'.format(meta.app_label, meta.object_name, field.name)
return Enum(name.upper(), choices, description=field.help_text)
return Enum(name.upper(), list(convert_choices(choices)), description=field.help_text)
return convert_django_field(field)


Expand Down
2 changes: 2 additions & 0 deletions graphene/contrib/django/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ class Article(models.Model):
('es', 'Spanish'),
('en', 'English')
], default='es')
importance = models.IntegerField('Importance', null=True, blank=True,
choices=[(1, u'Very important'), (2, u'Not as important')])

def __str__(self): # __unicode__ on Python 2
return self.headline
Expand Down
4 changes: 2 additions & 2 deletions graphene/contrib/django/tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ class Meta:
assert issubclass(graphene_type, graphene.Enum)
assert graphene_type._meta.type_name == 'TEST_TRANSLATEDMODEL_LANGUAGE'
assert graphene_type._meta.description == 'Language'
assert graphene_type.__enum__.__members__['es'].value == 'Spanish'
assert graphene_type.__enum__.__members__['en'].value == 'English'
assert graphene_type.__enum__.__members__['SPANISH'].value == 'es'
assert graphene_type.__enum__.__members__['ENGLISH'].value == 'en'


def test_should_float_convert_float():
Expand Down

0 comments on commit 68a9fb9

Please sign in to comment.