aalberti333
aalberti333

Reputation: 1229

Calling filters in django-graphene with GraphQL

I've been following the documentation for Graphene-Python in Django, and have just made it to the section on custom filters. While a tutorial is provided for how to write custom filters, there isn't a reference on how to call them in GraphiQL. If I have the following example code:

class AnimalNode(DjangoObjectType):
    class Meta:
        # Assume you have an Animal model defined with the following fields
        model = Animal
        filter_fields = ['name', 'genus', 'is_domesticated']
        interfaces = (relay.Node, )


class AnimalFilter(django_filters.FilterSet):
    # Do case-insensitive lookups on 'name'
    name = django_filters.CharFilter(lookup_expr=['iexact'])

    class Meta:
        model = Animal
        fields = ['name', 'genus', 'is_domesticated']

    @property  # make your own filter like this
    def qs(self):
        return super(EquityFilter, self).qs.filter(id=self.request.user)


class Query(ObjectType):
    animal = relay.Node.Field(AnimalNode)
    # We specify our custom AnimalFilter using the filterset_class param
    all_animals = DjangoFilterConnectionField(AnimalNode,
                                              filterset_class=AnimalFilter)

My question is, what would I need to type in GraphiQL to use this filter? Any help is greatly appreciated.

Upvotes: 2

Views: 1685

Answers (1)

greenLED
greenLED

Reputation: 381

Inspect the schema in GraphiQL. It should show a root query similar to this one:

allAnimals(
  before:String,
  after:String,
  firts:Int,
  last:Int,
  name:String,
  genus:String,
  isDomesticated:Boolean
):AnimalNodeConnection

The three filter criteria are exposed as query parameters, so you can use them with a query like this one:

query filteredAnimals{
  allAnimals(
    name:"Big Foot",
    genus:"Unknown",
    isDomesticated:false
  ) {
    edges {
      node {
        name
        genus
        isDomesticated
      }
    }
  }
}

Which will give you a connection with undomesticated animals named "Big Foot" ("big FOOT", "Big foot", etc.) with genus equal to "Unknown".

Note: Filters declared on the FilterSet Meta class are named after the type of filtering they do, like name_Icontains, name_Iexact. Filters declared as FilterSet fields (name filter in your case) keep their names unmodified, and extend or OVERRIDE filters declared in the FilterSet Meta class.

Upvotes: 2

Related Questions