Don't break on inherited choices fields.

Store converted Django fields in the registry, so choices enums are not
created multiple times when inherited by child models.
This commit is contained in:
Abram Booth 2017-04-21 13:25:30 -04:00
parent 2929d0866c
commit be20450a66
3 changed files with 49 additions and 3 deletions

View File

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

View File

@ -2,7 +2,7 @@ class Registry(object):
def __init__(self): def __init__(self):
self._registry = {} self._registry = {}
self._registry_models = {} self._field_registry = {}
def register(self, cls): def register(self, cls):
from .types import DjangoObjectType from .types import DjangoObjectType
@ -19,6 +19,12 @@ class Registry(object):
def get_type_for_model(self, model): def get_type_for_model(self, model):
return self._registry.get(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 registry = None

View File

@ -747,3 +747,35 @@ def test_should_query_dataloader_fields():
result = schema.execute(query) result = schema.execute(query)
assert not result.errors assert not result.errors
assert result.data == expected 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