Last active
June 3, 2021 19:12
-
-
Save denis-ryzhkov/fcb944f6ebfad4775efb74848703f0d7 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
You can put the function anywhere and in the __init__.py
of your app you call it with patch_graphene_django_choices_converter()
.
I'm currently working on integrating this great solution in the graphene-django
project. Hopefully this will make it's way to the master branch at some point: https://github.com/GitRon/graphene-django/blob/feature/modelform-fixes/graphene_django/converter.py
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello! I come from an issue where you placed the link to this gist, I do not know in which part of my project I should place it