Closed
Description
Having a field model with choices like the following:
class Question(models.Model):
TYPE_CHECKBOX = "checkbox"
TYPE_INTEGER = "integer"
TYPE_CHOICES = (
TYPE_CHECKBOX,
TYPE_INTEGER,
TYPE_FLOAT,
TYPE_RADIO,
TYPE_TEXTAREA,
TYPE_TEXT,
)
TYPE_CHOICES_TUPLE = ((type_choice, type_choice) for type_choice in TYPE_CHOICES)
type = models.CharField(choices=TYPE_CHOICES_TUPLE, max_length=10)
would lead to enum type with uppercased options. Rest Framework SerializerMutation
will expose this as graphene.String
and expects value to be lower case.
Adding following serializer converter solves this problem, so a choices field will expose as correct enum type also in mutations:
@serializer_converter.get_graphene_type_from_serializer_field.register(
serializers.ChoiceField
)
def convert_serializer_field_to_enum(field):
model_class = None
serializer_meta = getattr(field.parent, "Meta", None)
if serializer_meta:
model_class = getattr(serializer_meta, "model", None)
if model_class:
registry = get_global_registry()
model_field = model_class._meta.get_field(field.source)
return type(convert_django_field_with_choices(model_field, registry))
return graphene.String
Restriction is that when someone overwrites ChoicesField
in serializer with a restricted set of options it will still use the same enum.
If the fix looks OK in general and there is a interest in this fix, I am happy to provide a PR. Let me know.