Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save denis-ryzhkov/fcb944f6ebfad4775efb74848703f0d7 to your computer and use it in GitHub Desktop.
Save denis-ryzhkov/fcb944f6ebfad4775efb74848703f0d7 to your computer and use it in GitHub Desktop.

Revisions

  1. denis-ryzhkov revised this gist May 11, 2018. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions patch_graphene_django_choices_converter.py
    Original file line number Diff line number Diff line change
    @@ -9,6 +9,9 @@ def patch_graphene_django_choices_converter():
    - 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
  2. denis-ryzhkov created this gist May 11, 2018.
    34 changes: 34 additions & 0 deletions patch_graphene_django_choices_converter.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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
    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