How to Filter QuerySets Dynamically in Django?

Published On: 14/11/2022 | Category: Django


Hi Dev,

In this post, we will learn how to filter querysets dynamically in django. We will look at example of django filter queryset dynamically. I explained simply step by step how to filter queryset django. We will look at example of django filter querysets dynamically example. Let's see bellow example django search filter example.

Dynamically filtering QuerySets is a very typical use case. Undoubtedly, there is a pluggable programme that can simplify your life. This guide explains how to add hassle-free filtering to your views using the django-filter app. I'll set up a user search view to demonstrate this technique.

Here i explained simply step by step example of how to filter querysets dynamically in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core

Step 3: Install Required Library

Install Django and its prerequisites:

pip install django-filter

Step 4: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
    'django_filter'
]

Step 5: Creating the filters.py

In this step we need to create filters.py file in your app directory..

core/filters.py
from django.contrib.auth.models import User
import django_filters

class UserFilter(django_filters.FilterSet):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', ]

Step 6: Creating the Views

In this step, we need to configure views. The currency_data page get the file of currency. function is basically and convert to the selected currencies the open the core/views.py file and add:

core/views.py
from django.contrib.auth.models import User
from django.shortcuts import render
from .filters import UserFilter

# Create View
def search(request):
    user_list = User.objects.all()
    user_filter = UserFilter(request.GET, queryset=user_list)
    return render(request, 'core/user_list.html', {'filter': user_filter})

Step 7: Creating the Templates

Next, open the core/user_list.html file and the add:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Filters</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <h4>How to Filter QuerySets Dynamically in Django? - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <form method = "get">
                            {{ filter.form.as_p }}
                            <button type="submit" class="btn btn-success">Submit</button>
                        </form>
                        <div class="row mt-2">
                            <div class="col-md-12">
                                {% for user in filter.qs %}
                                    <p>{{ user.username }} - {{ user.get_full_name }}</p>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">
    $('input').addClass('form-control');
</script>
</html>

Step 8: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^search/$', views.search, name='search'),
]

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/search/ address with a web browser.

I hope it will help you....

Happy Coding!