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.
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
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
We are using the
surname__startswith argument and passing it surname to extract all student records that begin with the surnames
When we go running the server, we see it returned two items.
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
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
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
We should have written this out first and passed the surname to the
Let’s go ahead and run this query, so we return the same results.
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
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.