16

While using graphene with Relay in django, there is an option to use filtering while querying the data.

class AnimalNode(DjangoObjectType):
    class Meta:
        model = Animal
        filter_fields = ['name', 'genus', 'is_domesticated']
        OR
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith'],
            'genus': ['exact'],
            'is_domesticated': ['exact'],
        }
        interfaces = (relay.Node, )

Is it possible to use filtering in this fashion while I'm not using relay or is it a relay-only feature? I don't see any filtering for non-relay in the graphene docs so can't really be sure how to proceed with this.

vins
  • 15,030
  • 3
  • 36
  • 47
Mehran
  • 1,264
  • 10
  • 27
  • 3
    You are correct that it's a relay-only feature. It is possible, however, to create a convoluted solution for somewhat generic filters, by adding a list of generic key/value pairs as described here https://stackoverflow.com/questions/51224477/django-graphene-passing-json-or-dict-data-as-input-for-mutation/51269035#51269035 to your query input, and using these parsed values as optional filters to a queryset. – Mark Chackerian Jul 21 '18 at 14:07
  • 3
    I stumbled across another package that does this: https://github.com/eamigo86/graphene-django-extras but I can't vouch for it. – Mark Chackerian Jul 26 '18 at 02:37
  • I'm using github.com/eamigo86/graphene-django-extras it's been super helpful and 0 issues. Actually the Django-graphene lib is worse off without it. – S.D. Jan 08 '23 at 01:04

1 Answers1

1

Absolutely, you can totally apply filtering to your data in Graphene-Django even if you're not using Relay. The fancy term here is filter_fields, which is a handy tool that lets you decide how you want to filter stuff when you're asking for data.

In your case, you've got this AnimalNode thing, right? Cool.

You can sort of tell it what fields you want to use for filtering, like 'name', 'genus', and 'is_domesticated'. You can even get a bit fancy and specify how you want to filter, like "exact", "icontains", or "istartswith".