From 81c9dc54f4e0f225f2afcac27d9b4c406f64a553 Mon Sep 17 00:00:00 2001 From: Dan Palmer Date: Thu, 19 Jul 2018 11:48:39 +0100 Subject: [PATCH] Support converters for custom fields with choices --- graphene_django/converter.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/graphene_django/converter.py b/graphene_django/converter.py index da73ede..3bc28ea 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -38,13 +38,25 @@ def get_choices(choices): yield name, value, description +class UnknownDjangoFieldException(Exception): + pass + + 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: + + try: + converted = convert_django_field(field, registry) + except UnknownDjangoFieldException: + choices = getattr(field, 'choices', None) + if not choices: + # We don't have a converter and can't convert automatically to an + # enum. + raise + meta = field.model._meta name = to_camel_case('{}_{}'.format(meta.object_name, field.name)) choices = list(get_choices(choices)) @@ -59,8 +71,7 @@ def convert_django_field_with_choices(field, registry=None): enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) 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 @@ -68,7 +79,7 @@ def convert_django_field_with_choices(field, registry=None): @singledispatch def convert_django_field(field, registry=None): - raise Exception( + raise UnknownDjangoFieldException( "Don't know how to convert the Django field %s (%s)" % (field, field.__class__))