In this Python Django tutorial, I will show how to use Python filter not in Django, where you will understand about ‘not in’ operator that somehow acts equivalent to the filter.
Additionally, you will understand how to use the ‘not in’ in the view and template of your Django project. Finally, you will learn about the filter method exclude() in Django.
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 the 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 the list
In this section, we’ll learn to use the Django filter or we can say the 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
- Using template
So, let’s understand each way using a few examples. But first set the project environment by following the below steps:
Open your command prompt and create a virtual environment named ‘env’ using the below code.
python -m venv env
Activate the environment.
env\Scripts\activate
Install the latest version of Django.
pip install django
Create a Django project ‘django_filter’ using the below command.
django-admin startproject django_filter .
Now create a Django app ‘django_notin’ using the below command.
python manage.py startapp django_notin
Then open the project in your preferred IDE such as Visual Studio Code and set the project and app-level URL patterns.
So open the urls.py file of your Django project ‘django_filter’ and add the following lines of code.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('django_notin.urls'))
]
Also set the URL at the app level, so create a new file urls.py in your Django app ‘django_notin’ and in that file add the following lines of code.
from django.urls import path
from .views import *
urlpatterns = [
path('', filter_app, name='filter_app')
]
Django filter not in list using views
Now create a view named ‘filter_app’ that contains a list of blog names and pass the blogs to the template filter_app.html.
So for the demonstration of the “not-in” operator which acts as a filter, here you will learn how to filter the list of data using the “not-in.
Open the views.py file of your Django app ‘django_notin’ and add the following lines of code.
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})
In the above code define the view named ‘filter_app’ that contains a list of blogs.
- In line 4 list of blogs is defined and this is the blogs where you apply the not-in operator to exclude any of the values from the list.
- Now in line 5, the code (“MySql” not in blogs) checks if the string ‘MySql’ is not in the blogs list, if the ‘MySql’ is in the list then it returns False otherwise True.
- The return value is saved in the variable result and then this value is passed as context to the template filter_app.html.
Also create the template file, that creates a new folder template in your Django app ‘django_notin’. In that folder create a new file filter_app.html and add the following lines of code.
<!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.
So run the Django server by running the below command in your terminal.
python manage.py runserver
After running the server go to the URL http://127.0.0.1:8000/ and you see the output as shown below.
As you can see the result is a False value which means the string ‘MySql’ exists in the blogs list. Here you can consider how ‘not in’ checks for the not existence of the specific value in the list and returns the boolean.
This means it filtres the value in the list, if that value exists in the list it returns False otherwise returns True.
Let’s take one more example and this time check with the list of integer values.
Add the following line of code in your view filter_app as shown below
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})
In the above code, line 4 defines the list of integer values and stores them in the order variable. Then in line 5 check if the value 99 is not present in the order list and if the value is not present then it returns True, otherwise False.
Also, modify the template filter_app.html file and add the following lines of code:
<!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.
Now again open the URL http://127.0.0.1:8000/ and you see the result as shown below.
From the above output result equal True means the value 99 doesn’t present the order list.
Django filter not in list using a template tag
In the above topics you used the ‘not in’ operator as a filter in your view function but you can also use it in the template with the help of the Django template tag.
Let’s see an example where you create a list of programming languages in your view named filter_app by adding the following code in your 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})
The above code passes the list of languages and the variable test that contains a single value in the list to the template ‘filter_app.html’.
Then add the following lines of code in the template 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 at line 13. The tag evaluates the variables, if the condition is “true” the block {{test}} is not present in language list {{languages}} is executed.
Otherwise, in case of a “false” value, the {% else %} part of the block {{test}} is present in the language list {{languages}} is executed.
In the above, you can see that the block {{test}} is not present in the language list {{languages}} is executed because the [‘C Sharp’] is not present in the list of languages.
Which means ‘not in’ within the {%if%} returns True value.
Take one more example and add the following lines of code to your 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})
In the above code with the view ‘filter_app’, the list of vowels and test list is defined and then these lists are passed as context to the filter_app.html page.
Also add the following code in 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>
Again go to the URL http://127.0.0.1:8000/ and see the output as shown below.
Read: Python Django random number
Django model filter not in
In this section, you’ll learn how to use the alternate method to 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. There is an exclude() method with the “in” lookup in Django.
The exclude method returns the objects that do not match the given parameters.
The syntax is given below:
queryset = model_name.objects.exclude(parameter__in=[])
Let’s see different examples to clearly understand the concept of “exclude()”.
Firstly, create the model with the name Employee in the model.py file of the app and add the following line of code.
from django.db import models
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)
Then, register the model. For this, add the following code in the admin.py file of the Django app ‘django_notin’.
from django.contrib import admin
from .models import Employee
class AdminEmployee(admin.ModelAdmin):
list_display = ['first_name', 'last_name', 'position', 'age']
admin.site.register(Employee, AdminEmployee)
Then open the Admin panel and add some of the records related to the Employee as shown in the below picture. If you want to know how to create an admin user, then refer to this tutorial Python admin
After adding records you see the page as shown below.
After that open the Python shell by running the below command in your terminal.
python manage.py shell
In this example, you’ll use the exclude method with the “in” field lookup. Here exclude some specific ages from the Age field.
# Import
from django_notin.models import Employee
# QuerySet
queryset = Employee.objects.exclude(Age__in=[28, 26])
print(queryset)
In the above code, simply use the exclude method with the “in” field lookup to select the objects which do not have age values like 28 and 26. It will return all two objects that do not have these age values.
Conclusion
In this Python Django Tutorial, you have learned “Python filter not in Django” and also learned how to use the “not in” in the view and the template side.
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
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk
Leave a Reply