DEV Community

Cover image for Resolving Type Name Collisions with Graphene Django Filter and Enums
Mohamed Sharif
Mohamed Sharif

Posted on

Resolving Type Name Collisions with Graphene Django Filter and Enums

Introduction

When using Graphene Django to build APIs on top of Django we might get typename collisions when using filter or models fields with choices. Usually the errors and warnings are:

TypeError: Found different types with the same name in the schema

UserWarning: The `filterset_class` argument without `filter_input_type_prefix` can result in different types with the same name in the schema. 
Enter fullscreen mode Exit fullscreen mode

Understanding the Problem:

When using Grapehene Django filtering, it auto-generates Graphql Input types for each FilterSet you use. If you use the same filter class in multiple root-level query fields, it will create the same input type for both.

Example


class PostFilter(django_filters.FilterSet):
    class Meta:
        model = Post
        fields = {'author': ['exact'], 'content': ['icontains']}


class Query(graphene.ObjectType):
    all_posts = AdvancedDjangoFilterConnectionField(PostNode)
    viewer_posts =AdvancedDjangoFilterConnectionField(PostNode)
Enter fullscreen mode Exit fullscreen mode

The code above will cause Django to throw an Assertion Error with Found different types with the same name in the schema. It will create a duplicate of PostNodeFilterInputType. When it converts a field with choices to a graphene.Enum, it creates a new type for this field

Solutions
GraphQl requires every type name to be unique. With graphene-django-filter now we can set filter_input_type_prefix for each field that uses the same filter class.

<ModelName><FieldName>ChoicesEnum

on Settings

GRAPHENE = {
"DJANGO_CHOICE_FIELD_ENUM_V3_NAMING": True,

On Query Class

class Query(MeQuery, graphene.ObjectType):
viewer_posts = AdvancedDjangoFilterConnectionField(PostNode,filter_input_type_prefix="viewer_posts")
    all_posts = AdvancedDjangoFilterConnectionField(PostNode,filter_input_type_prefix="all_posts") 
Enter fullscreen mode Exit fullscreen mode

DjangoDocs

graphene-django-filter onPyPi

Connect with me on Linkedin

Top comments (0)