Search code examples
graphqlgraphene-django

How to resolve graphene.Union Type?


I want to create a UnionType(graphene.Union) of two existing types (FirstType and SecondType) and be able to resolve the query of this union type.


Schema

    class FirstType(DjangoObjectType):
        class Meta:
            model = FirstModel

    class SecondType(DjangoObjectType):
        class Meta:
            model = SecondModel

    class UnionType(graphene.Union):
        class Meta:
            types = (FirstType, SecondType)

So with this schema I want to query all objects from FirstType and SecondType with pk in some list [pks]

    query {
        all_items(pks: [1,2,5,7]){
          ... on FirstType{
             pk,
             color, 
          }

          ... on SecondType{       
             pk,        
             size,
          }
        }
     }

PKs from FirstType are normally not in the SecondType.

I tried like one below

    def resolve_items(root, info, ids):
        queryset1 = FirstModel.objects.filter(id__in=pks)
        queryset2 = SecondModel.objects.filter(id__in=pks)
        return queryset1 | queryset2

but it gives an error: 'Cannot combine queries on two different base models.'

I expect the following response from query:

    { 'data':
        {'all_items':[
           {'pk': 1,
            'color': blue
           },
           {'pk': 2,
            'size': 50.0
           },
           ...
          ]}
     }

So how the resolver should look like?


Solution

  • Okay, so I was too concentrated on merging query sets and I didn't notice that I can simply return a list.

    So here is solution which gives me the response I was looking for:

    def resolve_items(root, info, ids):
        items = []
        queryset1 = FirstModel.objects.filter(id__in=pks)
        items.extend(queryset1)
        queryset2 = SecondModel.objects.filter(id__in=pks)
        items.extend(queryset2)
        return items