Definition of Django Filter
Django is an open-source tool that provides different features to the user; that filter is one of the features that Django provides. It is a generic filter; with the help of the filter, we can make a reusable application, or we can say that we can view code as per our requirement. The Django filter is used to filter query sets that are based on the fields of models. Suppose we have n number of fields and we want to search users based on their names, we can apply the filter.
Overview of Django Filter
- Django-channel is a reusable Django application permitting clients to add dynamic QuerySet sifting from URL boundaries definitively.
- Django-Filter is a full-grown and stable bundle. It utilizes a two-section CalVer forming plan, for example. The primary number is the year. The second is the delivery number soon.
On an ongoing premise, Django-Filter plans to help all ongoing Django renditions, the matching current Python variants, and the most recent form of Django REST Framework.
The default conduct of the REST system’s nonexclusive rundown sees it is to return the whole query set for a model director. You will frequently believe your API should limit the things returned by the queryset.
The least complex method for separating the queryset of any view that subclasses GenericAPIView is to abrogate the .get_queryset() technique.
Superseding this technique permits you to tweak the queryset returned by the view in various ways. It supports the Python system,
- filter (): This technique returns another QuerySet with objects that match the given boundary. What’s more, it will likewise return a QuerySet in any event when there is just a single item that matches the condition. In such cases, the QuerySet will contain just a single component.
How to use the Django filter?
Now let’s see how we can use the Django filter as follows. First, we need to install the Django filter with the help of the below command as follows.
pip install django-filter
After installing the Django filter, we need to add django_filter inside the application. Now let’s see the usage of filters as follows.
Here we use a generic interface that is similar to the admin of Dango, which is the list_filter interface. It uses the same API very similar to the ModelForm of Django.
Let’s suppose we have a student model, and we need to filter data with the different parameters. At that time we can use the following code.
import django_filters
class StudentFilter(django_filters.FilterSet):
class Meta:
model = Student
fields = ['studname', 'class', 'city']
Explanation
In the above example, we can see that here we have a student model, and it has different fields as shown. If we need to view that code, then we need to use the following code.
def student_list(request):
filter = StudentFilter(request.GET, queryset = Student.objects.all())
return render(request, 'project/home.html',{'filter':filter})
Now let’s see how we can use the Django REST framework.
If we want to filter the backend for the REST framework, then we can use this structure. Basically, it provides the custom option to the filter set.
from django_filters import rest_framework as filters
class StudentFilter(filters.FilterSet):
class Meta:
model = Student
fields = ('Marks', 'table_result')
Explanation
In the above example, first, we need to import the
django_filters.rest_framework.FilterSet, and here we also need to specify the fields as per our requirement as shown.
Examples
Now let’s see different examples to understand filters as follows.
Suppose we have a database of students, and we need to filter students whose names start with Jenny. Then we need to use the following code as follows.
First, we must create a Python file and write the code below as follows.
from django.http import HttpResponse
from django.template import loader
from .models import Members
def sample(request):
mdata = Members.objects.filter(studname='Jenny').values()
template = loader.get_template('home.html')
context = {
'm_members': mdata,
}
return HttpResponse(template.render(context, request))
Explanation
In the above code, we write a queryset to filter the student name with Jenny. So here, first we need to import the different packages, and after that, we create a definition. Here we called the home.html file, so we need to write the following code to see the result.
So create a home.html file and write the following code as follows.
!DOCTYPE html>
<html>
<body>
<p>Final Result of query set is:</p>
{
{{List of students whose name start with Jenny}}
<p>Result of filter with loop:</p>
<table border='2'>
<tr>
<th>roll_no</th>
<th>studname</th>
<th>studname</th>
</tr>
{% for i in m_members %}
<tr>
<td>{{ i.roll_no }}</td>
<td>{{ i.studname }}</td>
<td>{{ i.studname }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
Explanation
In the HTML file, we can try to display the result of filterset; here we created a table to see the result with field names that are roll_no, surname, and studlastname as shown. The result of the above implementation we can see in the below screenshot is as follows.
Django Filter Chaining
In the above example, we see the sample can be a common case of filter, but chaining is another concept that we need to fetch the records from the different tables that we can join and use the ForeignKeys concept. Now let’s see an example as follows.
First, let’s see by using Django:
student.object.filter(studname = 'Jenny').filter(studage = 25)
The above statement is equivalent to the following statement as follows.
select "student"."roll_no",
"student"."studname",
"student"."studage"
from "student"
where("student"."studname" = Jenny AND "student"."studage" = 25)
Explanation
Now create a model to see the result of the above implementation as follows.
Class student(Model):
studname = CharFiled(max_length = 255)
studage = PositiveIntegerField()
We need to create an HTML file to see the result, here, I directly displayed the result, but we need to create an HTML file like the above example. The result of the above implementation can be seen in the below screenshot as follows.
Now let’s filter chaining by using Q expressions as follows.
Student.objects.filter(
Q(stud_stand = 'Class' )&
Q(studname = 'Jenny'))
Now let’s filter chaining by using kwargs as follows.
Student.objects.filter(
stud_stand = 'Class'
studname = 'Jenny'
)
Now let’s filter chain as follows.
Student.objects.f\
.filter(stud_stand = 'Class')\
.filter(studname = 'Jenny')
Conclusion
With the help of the above article, we try to learn about the Django filter. From this article, we learn basic things about the Django filter, and we also see the features and examples of the Django filter and how we use it in the Django filter.