11import inspect
2- from collections .abc import Callable
32from functools import partial , singledispatch , wraps
43
54from django .db import models
3736 from graphql import assert_valid_name as assert_name
3837from graphql .pyutils import register_description
3938
40- from .compat import ArrayField , HStoreField , RangeField
39+ from .compat import ArrayField , HStoreField , RangeField , normalize_choices
4140from .fields import DjangoConnectionField , DjangoListField
4241from .settings import graphene_settings
4342from .utils .str_converters import to_const
@@ -61,6 +60,24 @@ def wrapped_resolver(*args, **kwargs):
6160 return blank_field_wrapper (resolver )
6261
6362
63+ class EnumValueField (Field ):
64+ def wrap_resolve (self , parent_resolver ):
65+ resolver = self .resolver or parent_resolver
66+
67+ # create custom resolver
68+ def enum_field_wrapper (func ):
69+ @wraps (func )
70+ def wrapped_resolver (* args , ** kwargs ):
71+ return_value = func (* args , ** kwargs )
72+ if isinstance (return_value , models .Choices ):
73+ return_value = return_value .value
74+ return return_value
75+
76+ return wrapped_resolver
77+
78+ return enum_field_wrapper (resolver )
79+
80+
6481def convert_choice_name (name ):
6582 name = to_const (force_str (name ))
6683 try :
@@ -72,15 +89,7 @@ def convert_choice_name(name):
7289
7390def get_choices (choices ):
7491 converted_names = []
75- if isinstance (choices , Callable ):
76- choices = choices ()
77-
78- # In restframework==3.15.0, choices are not passed
79- # as OrderedDict anymore, so it's safer to check
80- # for a dict
81- if isinstance (choices , dict ):
82- choices = choices .items ()
83-
92+ choices = normalize_choices (choices )
8493 for value , help_text in choices :
8594 if isinstance (help_text , (tuple , list )):
8695 yield from get_choices (help_text )
@@ -157,7 +166,7 @@ def convert_django_field_with_choices(
157166
158167 converted = EnumCls (
159168 description = get_django_field_description (field ), required = required
160- ).mount_as (BlankValueField )
169+ ).mount_as (EnumValueField )
161170 else :
162171 converted = convert_django_field (field , registry )
163172 if registry is not None :
0 commit comments