Python server programming: data filtering using django-filter

WBOY
Release: 2023-06-18 12:52:40
Original
3731 people have browsed it

Python is a high-level programming language that has become more and more widely used in recent years. Especially in server-side programming, Python's elegance and efficiency are favored by developers.

This article will introduce an important tool in Python server-side programming-django-filter from the perspective of data filtering. We will introduce the basic usage, advanced usage, extended usage, etc. of django-filter to help you better use it in Python server-side programming.

1. What is django-filter

django-filter is a third-party application in the Django framework. It provides a simple and flexible filter system that allows developers to easily Filter and sort data easily. In the Django framework, the data filtering function can be easily implemented using django-filter, which is an indispensable tool for developers.

2. Basic usage of django-filter

Before using django-filter, you need to install the django-filter library:

pip install django-filter
Copy after login

The basic steps for using django-filter are as follows shown.

1. Create the FilterSet class

First, you need to create a FilterSet class to define the filter. A FilterSet class corresponds to a data model and can define which fields can be used for filtering, how to filter fields, etc.

For example, we have a simple student model:

class Student(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    grade = models.CharField(max_length=20)
Copy after login

Then, we can create a FilterSet class and define three fields name, age and grade, which can all be used as filters:

import django_filters

class StudentFilter(django_filters.FilterSet):
    class Meta:
        model = Student
        fields = ['name', 'age', 'grade']
Copy after login

2. Use the FilterSet class in the view function

Next, use the FilterSet class in the view function. You can create a FilterSet object, pass it to a QuerySet object, and then use it to obtain filtered data.

from django.shortcuts import render
from django_filters.views import FilterView

def student_list(request):
    f = StudentFilter(request.GET, queryset=Student.objects.all())
    return render(request, 'student_list.html', {'filter': f})
Copy after login

In this function, we use the FilterView view class, which is a view class provided in django-filter. FilterView helps us handle GET requests and user interactions, and returns processed data.

Notice that we pass request.GET and Student.objects.all() to the FilterSet object to obtain the filter parameters passed by the user and the QuerySet objects of all student data.

3. Use the FilterSet class in the template

Finally, you need to bind the filter to the template. In the template, you can get user input from the user by providing an HTML form to the filter and send it back to the view function.

<form method="get">
    {{ filter.form.as_p }}
    <button type="submit">搜索</button>
</form>

{% if filter.qs %}
    <ul>
        {% for student in filter.qs %}
            <li>{{ student.name }} - {{ student.age }} - {{ student.grade }}</li>
        {% endfor %}
    </ul>
{% else %}
    <p>没有符合条件的数据!</p>
{% endif %}
Copy after login

In the template, we display the filter form in the template through {{ filter.form.as_p }}. When the user submits the form, we will continue to use the FilterSet object to obtain the filtered data based on the user's input and return it to the template.

3. Advanced usage of django-filter

django-filter provides many advanced functions to help developers better filter data. In this section, we will introduce three advanced usages: custom filters, using multiple filter conditions and using ModelChoiceFilter in a FilterSet.

1. Custom filters

First, let’s introduce how to customize filters. Sometimes, the built-in filters provided to us do not meet our needs. Therefore, we need to customize the filter to better implement our ideas.

from django.db import models
import django_filters

class StudentFilter(django_filters.FilterSet):
    GRADE_CHOICES = (
        ('1', '一年级'),
        ('2', '二年级'),
        ('3', '三年级'),
        ('4', '四年级'),
        ('5', '五年级'),
        ('6', '六年级'),
    )

    grade__gte = django_filters.ChoiceFilter(label='入学年级', choices=GRADE_CHOICES)
    age__gte = django_filters.NumberFilter(label='年龄', lookup_expr='gte')

    class Meta:
        model = Student
        fields = ['grade', 'age']

    def filter_grade__gte(self, queryset, name, value):
        if value:
            return queryset.filter(grade__gte=int(value))
        return queryset
Copy after login

In this example, we define two custom filters grade__gte and age__gte. grade__gte is a selection filter and age__gte is a numeric filter. We also define a filter_grade__gte method to implement the logic of the custom filter. In this example, we use a simple if/else to filter the data. You can implement custom filter logic in the filter method according to your needs.

2. Multiple filtering conditions

Sometimes, we need to use multiple filtering conditions in the same filter to filter data. Fortunately, django-filter allows us to use multiple filter conditions to meet this need.

from django.db import models
import django_filters

class StudentFilter(django_filters.FilterSet):
    grade = django_filters.CharFilter(label='入学年级', lookup_expr='startswith')
    age = django_filters.NumberFilter(label='年龄', lookup_expr='lte')

    class Meta:
        model = Student
        fields = ['grade', 'age']
Copy after login

In this example, we define two filter conditions grade and age. Grade uses startswith to find, and age uses lte to find. You can define different search methods according to your needs and use them in FilterSet.

3. ModelChoiceFilter

In some cases, we need to use a ModelChoiceFilter filter to select model instances. ModelChoiceFilter allows us to process our data using the model's foreign key lookups etc.

from django.db import models
import django_filters

class GradeFilter(django_filters.FilterSet):
    name = django_filters.ModelChoiceFilter(queryset=Grade.objects.all())

    class Meta:
        model = Grade
        fields = ['name']
Copy after login

In this example, we use ModelChoiceFilter to filter Grade instances with a specific grade name. We can use the queryset attribute to set the object to look for, and then use the ModelChoiceFilter filter in the FilterSet class.

Summary

This article introduces an important tool in Python server programming-django-filter. We introduced the basic usage, advanced usage, extended usage, etc. of django-filter in detail. I hope this content will be helpful to you in implementing data filtering functions in Python server-side programming.

The above is the detailed content of Python server programming: data filtering using django-filter. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!