1+ from collections import OrderedDict
12from django .db import models
23from django .utils .encoding import force_text
34from django .utils .functional import Promise
@@ -39,6 +40,8 @@ def convert_choice_name(name):
3940
4041def get_choices (choices ):
4142 converted_names = []
43+ if isinstance (choices , OrderedDict ):
44+ choices = choices .items ()
4245 for value , help_text in choices :
4346 if isinstance (help_text , (tuple , list )):
4447 for choice in get_choices (help_text ):
@@ -52,6 +55,19 @@ def get_choices(choices):
5255 yield name , value , description
5356
5457
58+ def convert_choices_to_named_enum_with_descriptions (name , choices ):
59+ choices = list (get_choices (choices ))
60+ named_choices = [(c [0 ], c [1 ]) for c in choices ]
61+ named_choices_descriptions = {c [0 ]: c [2 ] for c in choices }
62+
63+ class EnumWithDescriptionsType (object ):
64+ @property
65+ def description (self ):
66+ return named_choices_descriptions [self .name ]
67+
68+ return Enum (name , list (named_choices ), type = EnumWithDescriptionsType )
69+
70+
5571def convert_django_field_with_choices (
5672 field , registry = None , convert_choices_to_enum = True
5773):
@@ -63,16 +79,7 @@ def convert_django_field_with_choices(
6379 if choices and convert_choices_to_enum :
6480 meta = field .model ._meta
6581 name = to_camel_case ("{}_{}" .format (meta .object_name , field .name ))
66- choices = list (get_choices (choices ))
67- named_choices = [(c [0 ], c [1 ]) for c in choices ]
68- named_choices_descriptions = {c [0 ]: c [2 ] for c in choices }
69-
70- class EnumWithDescriptionsType (object ):
71- @property
72- def description (self ):
73- return named_choices_descriptions [self .name ]
74-
75- enum = Enum (name , list (named_choices ), type = EnumWithDescriptionsType )
82+ enum = convert_choices_to_named_enum_with_descriptions (name , choices )
7683 required = not (field .blank or field .null )
7784 converted = enum (description = field .help_text , required = required )
7885 else :
@@ -235,12 +242,12 @@ def convert_postgres_array_to_list(field, registry=None):
235242
236243@convert_django_field .register (HStoreField )
237244@convert_django_field .register (JSONField )
238- def convert_posgres_field_to_string (field , registry = None ):
245+ def convert_postgres_field_to_string (field , registry = None ):
239246 return JSONString (description = field .help_text , required = not field .null )
240247
241248
242249@convert_django_field .register (RangeField )
243- def convert_posgres_range_to_string (field , registry = None ):
250+ def convert_postgres_range_to_string (field , registry = None ):
244251 inner_type = convert_django_field (field .base_field )
245252 if not isinstance (inner_type , (List , NonNull )):
246253 inner_type = type (inner_type )
0 commit comments