Support converters for custom fields with choices

This commit is contained in:
Dan Palmer 2018-07-19 11:48:39 +01:00 committed by GitHub
parent 06ca766c38
commit 81c9dc54f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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
try:
converted = convert_django_field(field, registry)
except UnknownDjangoFieldException:
choices = getattr(field, 'choices', None)
if choices:
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__))