Django OR Filter

Salman Mehmood Jun 15, 2022
Django OR Filter

We will learn with this quick and easy explanation about how to execute filters with an OR statement individually, and we will also look at how we execute the filters with a Q object in the Django queryset.

Use Filter to Execute OR Statement Individually and With Q Object in Django Queryset

In this example, we will use the database we created that has been added with some data and show you what this looks like.

Sample Data Table

We create a basic example; we will create a variable called posts and save all the data inside this variable. We will run a filter that will allow us to create a simple OR statement.

First, we need to select what we want to make an OR statement about, so let’s collect all the students’ names, starting with either austin or baldwin.

We are using the surname__startswith argument and passing it surname to extract all student records that begin with the surnames austin and baldwin.

extract all student records with or

When we go running the server, we see it returned two items.

output of 1st code

We have seen a basic example with an OR statement, but we could add another filter and more OR statements. Now we will work on one more example of using an OR statement, but this time we are using a Q object.

This is not a detailed demonstration of a queue object, but we will say it allows us to build more complex queries utilizing Q objects. We will show you an example of utilizing Q objects.

The code instruction is almost the same, we are just going to wrap everything around a Q object, and after the | operator, we will add another Q object. We do not need to add Student.objects.filter() again.

We should have written this out first and passed the surname to the surname__startswith argument.

extract all student records with or and q

Let’s go ahead and run this query, so we return the same results.

output of 2nd code

If we want to extend this, we can keep adding to this OR statement as often as we like. We added the not ~Q, which means select all students except where the surname begins with baldwin.

extract all student records with or and not q

Now we can see that all baldwin is no longer being shown because we define ~, which is used to remove or not select an item from the database.

output of 3rd code

Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn