Skip to content
thesarfo

Note

Q Objects for Complex Filtering

Combining filter conditions with OR/AND/AND-NOT using Q objects and the bitwise |, &, and &~ operators.

views 0

Applying Multiple Filters

Lets say you want to find all the products with inventory < 10 and unit_price < 20. Lets explore how to do this

  1. Pass multiple keyword arguments.
queryset = Product.objects.filter(inventory__lt=10, unit_price__lt=20)
  1. Instead of multiple keyword arguments, chain the call to filter method. ie, filtering the filter
queryset = Product.objects.filter(inventory__lt=10).filter(unit_price__lt=20)

If you look at the sql queries for the above methods, it combines the “and” condition. What if we want to combine the “or” condition.

We use something called Q objects in Django. First import it with

from django.db.models import Q

Q is short for query, and using this class we can represent a query expression or a piece of code that produces a value.

So using the Q class we can encapsulate a keyword argument.

queryset = Product.objects.filter(Q(inventory__lt=10) | Q(unit_price__lt=20))

What the above code is that, we have encapsulated the keyword argument inside a Q object, and then we use the bitwise or (|) operator to combine two combine another Q object. Using the bitwise or operator translates the logical OR in a sql query.

We can also use the & operator to do the same with AND. We can also use the &~ for AND NOT