How to Perform AND and OR logic operations with Q Lookups in Django
In this article, we show how to perform complex Q lookups that implement the AND and OR logic operations in Django.
Q lookups are a way in Django to search through database tables (or models) for information. One or multiple columns of a model can be searched by utilizing Q lookups.
A basic search using Q lookups in Django is shown below.
Let's imagine there's a model called Post that lists all the posts of the site.
Now let's say we want to search the column, name, of this model.
The code would be as follows.
In this code, we have a variable, lookups, that queries the name column of the model for anything that contains the query that a user looks up. query is a variable that contains the data that a user has entered into a text field to search for a term.
We then get the results and store it in the results variable. These will be all the objects that have a name matching the query.
Again, this is the most basic Q lookup.
Let's go to more advanced Q lookups.
AND Operator
Next, we show how to do AND operations with Q lookups.
The symbol to do an AND operation is a single ampersand (&).
So if we wanted to check if a Q lookup has 2 words in it, we could use the following code shown
below.
So now the query must contain both words in order to return a result.
OR Operator
Next, we show how to do OR operations with Q lookups.
The symbol to do an OR operation is |.
So if we wanted to check if a Q lookup has either word present in it, we could use the following code shown
below.
So now the query must contain either the first word or the second word to be returned as a result.
And of course you can mix and match both the AND and OR operators within a query.
This is shown in the following code below.
In the example above, only results are returned in which both words are in the title or both words are in the content of the post.
And this is how we can perform more advanced search lookups in Django with Q lookups,
including AND and OR operations.
Related Resources
How to Randomly Select From or Shuffle a List in Python