Biagio Distefano
Biagio Distefano

Reputation: 150

Django-graphene: how to filter with an OR operator

I am pretty new with both Django and Graphene, and couldn't get around a problem which might be fairly simple, but I had no luck with the docs or google to get an answer.

Let's say I have the following model:

class Law(models.Model):
    year = models.IntegerField(default=None)
    number = models.IntegerField(default=None)
    description = TextField(default=None)
    body = models.TextField(default=None)

And the following schema:

class LawType(DjangoObjectType):
    class Meta:
        model = models.Law
        filter_fields = {
            "year": ["exact"],
            "number": ["exact"],
            "description": ["contains"],
            "body": ["icontains"],
        }
        interfaces = (graphene.Node, )

class Query(graphene.AbstractType):
    all_laws = DjangoFilterConnectionField(LawType)

    def resolve_all_laws(self, args, context, info):
        return models.Law.objects.all()

How do I make a query or define a FilterSet class so that it will return a list of objects such that a word is found in the description or in the body?

{
    allLaws(description_Icontains: "criminal", body_Icontains: "criminal") {
        edges{
            node{
                year
                number
            }
        }
    }
}

I couldn't find an answer in the graphene-django documentation nor in the django-filter documentation.

Any clues? Thanks in advance

Upvotes: 2

Views: 2176

Answers (1)

souldeux
souldeux

Reputation: 3755

You can do this with the base Django framework by using a Q object: https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects

For instance, this statement would yield a single Q object representing the OR of the two queries:

Q(description__icontains='criminal') | Q(body__icontains='criminal')

You can pass this statement into a filter query:

Law.objects.filter(
    Q(description__icontains='criminal') | Q(body__icontains='criminal')
)

Upvotes: 2

Related Questions