2022年3月25日 12:02 by wst
djangoweb开发中根据前端传的参数过滤数据是很常见的。
在Django中,插件(django-filter)对这个功能进行了加强。
下面列出常见用法:
1. 安装插件:
pip install django-filter
2. 添加配置(settings.py)
INSTALLED_APPS = [
...
'django_filters',
]
REST_FRAMEWORK = {
# 过滤器默认后端
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',),
}
3. 定义模型(models.py)
from django.db import models
# Create your models here.
class BookInfo(models.Model):
btitle = models.CharField(max_length=20, verbose_name="名称")
bpub_date = models.DateField(verbose_name="发布日期")
bread = models.IntegerField(default=0, verbose_name="阅读量")
bcomment = models.IntegerField(default=0, verbose_name="评论量")
is_delete = models.BooleanField(default=False, verbose_name="逻辑删除")
4. 定义序列化类(serializer.py)
from rest_framework import serializers
class BookInfoSerializer(serializers.Serializer):
# read_only = True 只读, label:字段说明信息
id = serializers.IntegerField(read_only=True, label="书籍编号")
btitle = serializers.CharField(max_length=20, min_length=3, label="名称")
bpub_date = serializers.DateField(label="发布日期")
bread = serializers.IntegerField(default=0, min_value=0, label="阅读量")
bcomment = serializers.IntegerField(default=0, max_value=50, label="评论量")
is_delete = serializers.BooleanField(default=False, label="逻辑删除")
5. 定义视图(views.py)
定义视图之前,假定过滤器(filters.py)已经存在(细节下面讲)。
from rest_framework.generics import ListAPIView
from .models import BookInfo
from .serializer import BookInfoSerializer
from .filters import BookFilter
class BookView(ListAPIView):
""" 图书查询"""
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
filter_class = BookFilter
1. 对字符串类型过滤、数值类型大小限制
from django_filters import rest_framework as filters
from .models import BookInfo
class BookFilter(filters.FilterSet):
min_read = filters.NumberFilter(field_name='bread', lookup_expr='gte')
max_read = filters.NumberFilter(field_name='bread', lookup_expr='lte')
class Meta:
model = BookInfo
fields = {
'btitle': ['icontains'],
'bcomment': ['gte', 'lte']
}
说明:
* 对bread字段进行限制,前端需要传递参数min_read(最小值), max_read(最大值);
* 对btitle字段进行限制,前端需要传递参数btitle__icontains(包含字符)
* 对bcomment进行限制,前端需要传递参数bcomment__gte(最小值),bcomment__lte(最大值)
* Meta中的fields变量一定要写,不写会报错,哪怕是个空数组:fields=[] 表示只对bread进行过滤,前端可以传两个参数min_read, max_read;
2. 默认进行精确查找
from django_filters import rest_framework as filters
from .models import BookInfo
class BookFilter(filters.FilterSet):
class Meta:
model = BookInfo
fields = [
'bpub_date', 'is_delete'
]
说明:
1. 对bpub_date精确查找,前端可传参数bpub_date;
2. 对is_delete精确查找,前端可传参数is_delete;
1. 最对某个模型的过滤,需要在Meta中体现,fields变量也要有;
2. fields变量必须有,可以为列表或者字典;
3. fields为列表,则需要包含被过滤的字段;
4. fields为字典,则key为需要过滤的字段,value为过滤方式;