mirror of
https://github.com/graphql-python/graphene.git
synced 2024-11-11 12:16:58 +03:00
Improved Django field choice converter
This commit is contained in:
parent
bd88f2327e
commit
68a9fb9fc4
|
@ -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)
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -103,8 +103,8 @@ def test_field_with_choices_convert_enum():
|
|||
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():
|
||||
|
|
Loading…
Reference in New Issue
Block a user