Search code examples
djangographqlgraphene-pythongraphene-django

How to return List of QuerySets in graphql query as separate list elements?


The problem I am facing is that I have custom_filter of MyModel which return the list of <QuerySet> like

[<QuerySet [<MyModel: xyz>]>, <QuerySet [<MyModel: xyz>, <MyModel: xyz>,<MyModel: xyz>]>]

The object type

class MyModelNode(DjangoObjectType):
    class Meta:
        model=MyModel
        filter_fields=['id]
        interfaces = (graphene.relay.Node,)


Query

class Query(graphene.ObjectType):
   my_model_items = graphene.List(MyModelNode)

   def resolve_my_model_items(self, info, **kwargs):
      my_model_filtered_items = MyModel.objects.custom_filter(kwargs)
      # my_model_filtered_items holds the list of querysets
      return my_model_filtered_items

How to handle list of querysets. The graphql respone of the query should give a list which have the querysets as elements.

[
  {
  //These are from first <QuerySet>
  "myModelItems":[
      {
        "fieldsIaskedFor":"response"
      }
    ]

  },


  {
  //These are from second <QuerySet>
  "myModelItems":[
      {
        "fieldsIaskedFor":"resp"
      },
      {
        "fieldsIaskedFor":"resp"
      },
      {
        "fieldsIaskedFor":"resp"
      },
    ]

  },


]

How to get results of different querysets in separate list elements ? The number of <QuerySet> are not fixed.

What I have to do to achieve that ?.


Solution

  • This can be done by creating two object types and simply nesting one inside other.

    The first object type will be the DjangoObjectType of MyModel

    class DjangoMyModelNode(DjangoObjectType):
        class Meta:
            model = MyModel
            filter_fields = ['id']
            interfaces = (graphene.relay.Node,)
    

    The second objects type will be a custom ObjectType

    class MyModelNode(graphene.ObjectType):
        my_model_items = graphene.List(DjangoMyModelNode)
    
        def resolve_my_model_items(self, info, **kwargs):
            return self
    

    The query will remain the same

    class Query(graphene.ObjectType):
        my_model_items = graphene.List(MyModelNode)
    
        def resolve_my_model_items(self, info, **kwargs):
            my_model_filtered_items = MyModel.objects.custom_filter(kwargs)
            # my_model_filtered_items holds the list of querysets
            return my_model_filtered_items
    
    

    This will return things according to desired result