Django Q function

When querying objects in django the simplest way is to use the filter() query.

If we have a set of systems for example and we want to filter out those that have a SPARC architecture we could do:

>>>  System.objects.filter(architecture="sparc")

And if we wanted to narrow that down to only sparc machines that use NIS for name resolution we could do:

System.objects.filter(architecture="sparc").filter(name_resolution="NIS")

But that is narrowing down the selection. It’s an AND. What were asking for is systems that are a SPARC _AND_ use NIS. And although we can use exclude() to reject some results it’s still and AND operation. What about an OR query?

What if we wanted to select systems that had either a T5 or a T7 processor? Then we need Q queries.

Q queries take the same form of argument as filter() & exclude() etc. but can be combined using OR operators. Here’s the Q query for our model that looks at the cpu_implementation for T5 or T7:

Q(sysconfig__icontains="T7") | Q(sysconfig__icontains="t5")

To build our query we just use this Q expression in a filter:

from django.db.models import Q
System.objects.filter(Q(sysconfig__icontains="T7")|Q(sysconfig__icontains="t5"))

Leave a Comment

Your email address will not be published. Required fields are marked *

Exit mobile version