Django has an inbuilt function for filtering the dataset. But it is lacking in the exclusion of dataset. So for this, we have other 2 solutions to filter out data which not equal to the mentioned dataset. Here, We are going to understand and learn through a mini Django project using Python. Let’s create a Django project to show “not equal in Python Django Queryset filtering”.
Basic Setup of the Django Project
Step 1: Create a virtual environment.
Step 2: To initiate a project Django on Your PC, open Terminal and enter the following command.
django-admin startproject projectName
Step 3: A New Folder with the name project name will be created and entered into a folder using the command.
cd projectName
Step 4: Create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command.
python manage.py startapp projectApp
You should get the folder structure like this
Step 5: To consider the app in your project you need to specify your project name in INSTALLED_APPS list as follows in settings.py.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app' ]
Step 6: Specify your templates directory in the TEMPLATES list as follows in settings.py.
Setting Paths and Models in Django
Step 7: Now in the list of URL patterns, you need to specify the app name in your urls.py.
Python3
from django.contrib import admin from django.urls import path, include urlpatterns = [ path( 'admin/' , admin.site.urls), path(' ', include(' app.urls')), ] |
Step 8: Create models in app/models.py
Python3
# app/models.py from django.db import models class User(models.Model): user_name = models.CharField(max_length = 20 ) city = models.CharField(max_length = 20 , blank = True , null = True ) country = models.CharField(max_length = 20 , blank = True , null = True ) |
Step 9: Register them on the admin site admin.py.
Python3
from django.contrib import admin from . models import User # Register your models here. admin.site.register(User) |
Step 10: Create a superuser by following the below command in the terminal.
python manage.py createsuperuser
Creating GUI for our Project
Step 11: Create a templates folder and inside that create a show_details.html file. Add the following code inside the templates/show_detatils.html file.
HTML
<!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 >Document</ title > </ head > < body > < h1 >User's Details</ h1 > < form action = "{% url 'show_all' %}" > {% csrf_token %} < button type = "submit" >Show all users</ button > < div style = "display:inline-block;" >{% for user in users %}{{user.user_name}}, {% endfor %}</ div > </ form > < br >< br > < form action = "{% url 'show_indians' %}" > {% csrf_token %} < button type = "submit" >Show Indians</ button > < div style = "display:inline-block;" >{% for user in show_indians %}{{user.user_name}}, {% endfor %}</ div > </ form > < br >< br > < form action = "{% url 'show_non_indians' %}" > {% csrf_token %} < button type = "submit" >Show Non Indians</ button > < div style = "display:inline-block;" >{% for user in show_non_indians %}{{user.user_name}}, {% endfor %}</ div > </ form > </ body > </ html > |
Python Django Queryset filtering
Step 12: To perform filter queries we have to first add some data to our user functions foe that we have created 3 functions. In the first function, we showed all the users that were registered. In the second, we filtered “Indian” by using the Python filter() function and Python exclude() function whereas in the third function we use tidal(~Q) to show Non-Indians.
Python3
from django.shortcuts import render, HttpResponse from . models import User from django.db.models import Q def show_all(request): # This command outputs all user objects # that we have created at start. users = User.objects. all () return render(request, 'show_details.html' , context = { 'users' : users}) def show_indians(request): # 1st solution show_indians = User.objects. filter ( country = 'India' ).exclude(country = 'Japan' ) # This command will retrieve indians nationality peoples return render(request, 'show_details.html' , context = { 'show_indians' : show_indians}) def show_non_indians(request): # 2nd Solution show_non_indians = User.objects. filter (~Q(country = 'India' )) # This command will retrieve non-indian nationality peoples return render(request, 'show_details.html' , context = { 'show_non_indians' : show_non_indians}) |
Step 13: Add the URLs and functions to maintain file paths in your app/urls.py.
Python3
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.show_all, name = "show_all" ), path( 'show_indians/' , views.show_indians, name = "show_indians" ), path( 'show_non_indians/' , views.show_non_indians, name = "show_non_indians" ) ] |
Migrate files in Django
Step 14: Migrate all the files to the database using the following commands.
python manage.py makemigrations python manage.py migrate
Deploy our App to Test Queryset Filtering
Step 15: Run the project using the below command, and hit the URL “http://127.0.0.1:8000/admin”. Enter the superuser credentials.
python manage.py runserver
Step 16: Now you can see under the App category there is a user model after clicking (http://127.0.0.1:8000/admin/app/user/add/) on that on the right-hand side you can see an add user option from there we can add the user’s data. we have added 2 users’ data one belongs to India and another to japan you can add more to your choice.
Step 17: You can see these outputs on the webpage on http://127.0.0.1:8000/
Output: