In this Django tutorial, we will understand the implementation of Python filter not in Django. And we will also discuss examples related to the not in filter in Django. Here is the list of topics that we are going to cover.
- Filter not in Django
- Django filter not in list
- Django model filter not in
Filter not in Django
In this section, we are going to discuss the “not in” filter in Django.
In Python Django, the “not in” filter or we can say that operator acts in the exact opposite way as the “in” filter. It tests for the presence of a specified value within a sequence, but the return values are the reverse of the “in” filter.
When the “not in” filter is used in the condition with the value present inside the sequence, the statement returns the boolean result False. Whereas when the value is not present inside the sequence, the statement returns the boolean result True.
From the sequence we mean, it can be lists, tuples, arrays, strings, dictionaries, etc.
Read: Python Django vs ReactJS
Django filter not in list
In this section, we’ll learn to use Django filter or we can say operator “not in” in the python list. And, in Django, the “not in” operators are commonly used in the if tags.
In Django, there are two ways to use the “not in” filter in the list:
- Using views
- Uisng template
So, let’s understand each way using a few examples.
Django filter not in list using views
Here we learn how to use the views while working on Django’s “not in” filter, in the Python list.
Before we start the demonstration, I’ll show you the project’s urls.py and app’s urls.py files, as it remains the same in all the examples.
Firstly, I create a Project and App with the name PythonGuides and filter_app respectively.
The PythonGuides urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('filter_app.urls'))
]
This means that when you open your project in the browser, it will take you to your filter_app.urls.
The filter_app urls.py file:
from django.urls import path, include
from filter_app import views
urlpatterns = [
path('', views.filter_app, name='filter_app')
]
It moves to the views.py file of the filter_app app.
Example #1
The views.py file:
from django.shortcuts import render
# Create your views here.
def filter_app(request):
blogs = ["Python", "MariaDB", "MySql", "Machine Learning", "PostgreSql"]
result = ("MySql" not in blogs )
return render(request, 'filter_app.html', {'result':result})
- We define the list of blogs and then use the “not in” operator.
- Then, we render the result on the HTML page.
The home.html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PythonGuides</title>
</head>
<body>
<font color="green">
Check MySql present in Blog or not (while using "not in" operator)
<br>
<br>
</font>
<font color="red">
<b> Result : </b>{{result}}
</font>
</body </html>
In the filter_app.html file, we are just using the variable to get the result. In the end, we will get the following output.
Example #2
The views.py file:
from django.shortcuts import render
# Create your views here.
def filter_app(request):
order = [100, 101, 102, 103, 104, 105]
result = (99 not in order)
return render(request, 'filter_app.html', {'result':result})
- We define the list of orders and then use the “not in” operator.
- Then, we render the result on the HTML page.
The home.html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PythonGuides</title>
</head>
<body>
<font color="green">
Check Order Number 99 present in Order or not (while using "not in" operator)
<br>
<br>
</font>
<font color="red">
<b> Result : </b>{{result}}
</font>
</body </html>
We simply use the variable to get the result in the filter_app.html file. Finally, we’ll get the following result.
Django filter not in list using template
Here we learn how to use the template tags while working on Django’s “not in” filter, in the Python list. Here I am using the same project’s urls.py and app’s urls.py files as used in views.
Example #1
The views.py file:
from django.shortcuts import render
# Create your views here.
def filter_app(request):
languages = ["C", "C++", "Python", "Java"]
test = ["C Sharp"]
return render(request, 'filter_app.html', {'languages': languages, 'test':test})
Firstly, we will create a view that will redirect to an HTML page. In the views.py file, we define the list and redirect the list to the filter_app.html page.
The filter_app.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PythonGuides</title>
</head>
<body>
<p>
{% if test is not languages %}
{{test}} is not present in language list {{languages}}
{% else %}
{{test}} is present in language list {{languages}}
{% endif %}
</p>
</body
</html>
Here, we add the “is not” operator in the template using the {%if%} tag. If the tag evaluates the variables, if the condition is “true” the contents of the block are output.
Example #2
The views.py file:
from django.shortcuts import render
# Create your views here.
def filter_app(request):
vowels = ["A", "E", "I", "O", "U"]
test = ["A"]
return render(request, 'filter_app.html', {'vowels': vowels, 'test':test})
Here, we’ll create a view that redirects to an HTML page. The list of vowels and test list is defined in the views.py file and redirected to the filter_app.html page.
The filter_app.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PythonGuides</title>
</head>
<body>
<p>
{% if test is not vowels %}
{{test}} is one of the five friend
{% else %}
{{test}} is not in the list of five friend
{% endif %}
</p>
</body
</html>
The output is as follow:
Read: Python Django random number
Django model filter not in
In this section, we’ll learn how to use the “not in” filter in Django models. In Django, “not in” means selecting the objects that contain the values that are not there in the given iterable.
Basically, In Django, we don’t have any filter with the name “not in”. So, to work in the same way as the “not in” filter works. We use exclude method with the “in” filter of Django.
Exclude method returns the objects that do not match the given parameters.
The syntax is like that:
queryset = model_name.objects.exclude(parameter__in=[])
Let’s see different examples to clearly understand the concept of “not in”.
For this, we will create an Employee model in Django.
Firstly, create the model with the name Employee in the model.py file of the app. And add the following code.
from django.db import models
# Create your models here.
class Employee(models.Model):
First_Name = models.CharField(max_length=200)
Last_Name = models.CharField(max_length=200)
Position = models.CharField(max_length=100)
Age = models.PositiveIntegerField()
def __str__(self):
return "%s %s %s %s" % (self.First_Name, self.Last_Name, self.Position, self.Age)
- Here we create a model, with respective fields such as First_Name, Last_Name, Position, Age.
Then, we register the model. For this, add the following code in the admin.py file of the app.
from django.contrib import admin
from .models import Employee
# Register your models here.
class AdminEmployee(admin.ModelAdmin):
list_display = ['First_Name', 'Last_Name', 'Position', 'Age']
admin.site.register(Employee, AdminEmployee)
Let’s have a look at Employee Model.
Example #1
In this example, we’ll use the exclude method with the “in” field lookup. Here we exclude some specific ages from the Age field.
# Import
from DjangoFilter.models import Employee
# QuerySet
queryset = Employee.objects.exclude(Age__in=[28, 26])
print(queryset)
In this example, we are simply using the exclude method with “in” field lookup to select the objects which do not have age values like 28 and 26. And it will return all two objects that do not have these age values.
The output is as below:
Example #2
Here we exclude some specific primary keys from the Employee model.
# Import
from DjangoFilter.models import Employee
# QuerySet
queryset = Employee.objects.exclude(pk__in=[1, 3, 5])
print(queryset)
We are just using the exclude method with the “in” field lookup in this example to select the items that do not have primary key values of 1, 3, and 5. It will return all two objects that have these key values.
The output is as below:
Example #3
Here we exclude some specific Position field values from the Employee model.
# Import
from DjangoFilter.models import Employee
# QuerySet
queryset = Employee.objects.exclude(Position__in=['Vice President'])
print(queryset)
We are just using the exclude method with “in” field lookup in this example to select the items that do not have Position value Vice President. It will return all the objects that have these key values.
Also, take a look at some more Django tutorials.
- Python Django set timezone
- Python Django format date
- Python Change Django Version
- Python Django vs Pyramid
- Union operation on models Django
In this Django Tutorial, we have discussed “Python filter not in Django” and we have also discussed the following topics in this tutorial.
- Filter not in Django
- Django filter not in list
- Django model filter not in
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.