Merge pull request #156 from aaxelb/master

Fix #87: Don't create duplicate Enums for fields with choices
This commit is contained in:
Syrus Akbary 2017-11-14 21:14:51 -08:00 committed by GitHub
commit 5661db88d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 3 deletions

View File

@ -40,6 +40,10 @@ def get_choices(choices):
def convert_django_field_with_choices(field, registry=None):
if registry is not None:
converted = registry.get_converted_field(field)
if converted:
return converted
choices = getattr(field, 'choices', None)
if choices:
meta = field.model._meta
@ -55,8 +59,12 @@ def convert_django_field_with_choices(field, registry=None):
return named_choices_descriptions[self.name]
enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType)
return enum(description=field.help_text, required=not field.null)
return convert_django_field(field, registry)
converted = enum(description=field.help_text, required=not field.null)
else:
converted = convert_django_field(field, registry)
if registry is not None:
registry.register_converted_field(field, converted)
return converted
@singledispatch

View File

@ -3,7 +3,7 @@ class Registry(object):
def __init__(self):
self._registry = {}
self._registry_models = {}
self._field_registry = {}
def register(self, cls):
from .types import DjangoObjectType
@ -20,6 +20,12 @@ class Registry(object):
def get_type_for_model(self, model):
return self._registry.get(model)
def register_converted_field(self, field, converted):
self._field_registry[field] = converted
def get_converted_field(self, field):
return self._field_registry.get(field)
registry = None

View File

@ -748,3 +748,35 @@ def test_should_query_dataloader_fields():
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_handle_inherited_choices():
class BaseModel(models.Model):
choice_field = models.IntegerField(choices=((0, 'zero'), (1, 'one')))
class ChildModel(BaseModel):
class Meta:
proxy = True
class BaseType(DjangoObjectType):
class Meta:
model = BaseModel
class ChildType(DjangoObjectType):
class Meta:
model = ChildModel
class Query(graphene.ObjectType):
base = graphene.Field(BaseType)
child = graphene.Field(ChildType)
schema = graphene.Schema(query=Query)
query = '''
query {
child {
choiceField
}
}
'''
result = schema.execute(query)
assert not result.errors