Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save W1773ND/c1f9bbbc2aebe81cdd8097afe323c3cd to your computer and use it in GitHub Desktop.
Save W1773ND/c1f9bbbc2aebe81cdd8097afe323c3cd to your computer and use it in GitHub Desktop.
Prevent `graphene_django` from converting Django `choices` to `graphene.Enum` constants: ints like 7 are not converted to "A_7", and so on
import graphene_django
def patch_graphene_django_choices_converter():
"""
Prevent `graphene_django` from converting Django `choices` to `graphene.Enum` constants
Pros:
- Ints like 7 are not converted to "A_7"
- Strings like "Some String" are not converted to "SOME_STRING"
- Values of any other type are kept as is too
- No more `AssertionError: Found different types with the same name in the schema: FooType, FooType`
when you have `choices` field `type` of model `Foo` which autogenerates `FooType` enum,
conflicting with your own `class FooType(DjangoObjectType)`
Cons:
- Client loses ability to get list of possible values from server via GraphQL introspection
(but still can do this via custom resolver)
"""
old_convert_django_field_with_choices = graphene_django.converter.convert_django_field_with_choices
def new_convert_django_field_with_choices(field, *args, **kwargs):
choices = getattr(field, 'choices', None)
if choices is None:
return old_convert_django_field_with_choices(field, *args, **kwargs)
del field.choices
try:
return old_convert_django_field_with_choices(field, *args, **kwargs)
finally:
field.choices = choices
graphene_django.converter.convert_django_field_with_choices = new_convert_django_field_with_choices
# It is important to patch `graphene_django.types` too:
# it imported old `convert_django_field_with_choices` already:
graphene_django.types.convert_django_field_with_choices = new_convert_django_field_with_choices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment