Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a query by a list of ids in GraphQL using graphene-django?

I'm trying to perform a GraphQL query using Django and Graphene. To query one single object using the id I did the following:

{
  samples(id:"U2FtcGxlU2V0VHlwZToxMjYw") {
    edges {
      nodes {
        name
      }
    }
  }
}

And it just works fine. Problem arise when I try to query with more than one id, like the following:

{
  samples(id_In:"U2FtcGxlU2V0VHlwZToxMjYw, U2FtcGxlU2V0VHlwZToxMjYx") {
    edges {
      nodes {
        name
      }
    }
  }
} 

In the latter case I got the following error:

argument should be a bytes-like object or ASCII string, not 'list'

And this is a sketch of how defined the Type and Query in django-graphene

class SampleType(DjangoObjectType):
  class Meta:
    model = Sample
    filter_fields = {
      'id': ['exact', 'in'],
     }
     interfaces = (graphene.relay.Node,)

class Query(object):
  samples = DjangoFilterConnectionField(SampleType)

  def resolve_sample_sets(self, info, **kwargs):
    return Sample.objects.all()
like image 898
ilmorez Avatar asked Jan 16 '19 13:01

ilmorez


2 Answers

GlobalIDMultipleChoiceFilter from django-graphene kinda solves this issue, if you put "in" in the field name. You can create filters like

from django_filters import FilterSet
from graphene_django.filter import GlobalIDMultipleChoiceFilter

class BookFilter(FilterSet):
    author = GlobalIDMultipleChoiceFilter()

and use it by

{
  books(author: ["<GlobalID1>", "<GlobalID2>"]) {
    edges {
      nodes {
        name
      }
    }
  }
}

Still not perfect, but the need for custom code is minimized.

like image 59
ulgens Avatar answered Oct 24 '22 04:10

ulgens


You can easily use a Filter just put this with your nodes.

class ReportFileFilter(FilterSet):
    id = GlobalIDMultipleChoiceFilter()

Then in your query just use -

class Query(graphene.ObjectType):
    all_report_files = DjangoFilterConnectionField(ReportFileNode, filterset_class=ReportFileFilter)

This is for relay implementation of graphql django.

like image 3
Ameya Marathe Avatar answered Oct 24 '22 04:10

Ameya Marathe