Django filter动态过滤与排序实现过程解析
作者:-零 时间:2022-01-07 18:16:54
前期准备
在虚拟开发环境中安装:
pip install django-filter
在Django的项目配置文件中安装并配置django_filters应用:
INSTALLED_APPS = [
...
'django_filters',
]
REST_FRAMEWORK = {
# 过滤器默认后端
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',),
}
快速使用
model.py
class User(models.Model):
# 模型字段
name = models.CharField(max_length=10, verbose_name="姓名")
sex = models.BooleanField(default=1, verbose_name="性别")
age = models.IntegerField(verbose_name="年龄")
phone = models.CharField(max_length=20, null=True, verbose_name="电话")
addr = models.CharField(max_length=100,null=True,verbose_name="地址")
class Meta:
db_table = "tb_user"
verbose_name = "用户"
verbose_name_plural = verbose_name
新建filter.py:过滤器类
import django_filters
from .models import User
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = ["name", "age"] #指定动态过滤的字段,默认精准匹配
注意:
Meta字段说明
model: 引用的模型,不是字符串
fields:指明过滤字段,可以是列表,列表中字典可以过滤,默认是判等;也可以字典,字典可以自定义操作
exclude = ['password'] 排除字段,不允许使用列表中字典进行过滤
view.py
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import ListAPIView
from rest_framework import filters
class UserViewSet(ListAPIView):
queryset = User.objects.all() #获取数据
serializer_class = UserModelSerializer #指定序列化类
filter_class = UserFilter # 指定过滤器类
serializers.py
from rest_framework import serializers
from .models import User
class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
urls.py
path('user/',UserViewSet.as_view()),
首先理解上面是动态过滤,前端在请求头如下传递参数,传递参数的个数是不同的,而动态过滤只会过滤:有参数,且参数有值的项。
http://ip:port/user/?name=查找内容&age=查找内容
http://ip:port/user/?name=&age=查找内容
http://ip:port/user/?name=查找内容&age=
http://ip:port/user/?name=&age=
http://ip:port/user/
精准过滤、模糊过滤并存
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
# fields = ["name", "age"]
fields = {
"name": ['exact','icontains'],
"age": ['exact'],
}
exact:默认过滤方式,精确过滤
icontains:模糊过滤
http://ip:port/user/?name=查找内容&name_icontains=查找内容&age=查找内容
范围过滤
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
# fields = ["name", "age"]
fields = {
"name": ['exact','icontains'],
"age": ['exact','gte','lte'],
}
对以上filter来说
name 精确查找
name__icontains 模糊查找
age 精准查找
age__gte 大于等于
age__lte 小于等于
排序
class UserFilter(django_filters.FilterSet):
#定义排序字段:依赖哪个字段排序
sort = django_filters.OrderingFilter(fields=('age',))
class Meta:
model = User
# fields = ["name", "age"]
fields = {
"name": ['exact','icontains'],
"age": ['exact','gte','lte'],
}
url示例
http://ip:port/user/?name=查找内容&sort=age:表示升序
http://ip:port/user/?name=查找内容&sort=-age:表示降序
补充知识
这部分可以参考:https://zhuanlan.zhihu.com/p/110060840
过滤器可以自定义字段,开始我们这样定义过滤字段,以及每个字段是相等运算,模糊匹配,还是范围查询,但是这样的写法可能不太直观。
fields = {
"name": ['exact','icontains'],
"age": ['exact','gte','lte'],
}
我们可以做如下类型改变
class BookFilter(filters.FilterSet):
btitle = filters.CharFilter(field_name='title',lookup_expr='icontains')
pub_year = filters.CharFilter(field_name='bpub_date',lookup_expr='year')
pub_year__gt = filters.CharFilter(field_name='bpub_date',lookup_expr='year__gt')
bread__gt = filters.NumberFilter(field_name='bread',lookup_expr="gt")
bread__lt = filters.NumberFilter(field_name='bread',lookup_expr="lt")
class Meta:
model = Bookinfo
fields = ['title','bread','bcomment']
http://127.0.0.1:8000/book/?title=&bread=&bcomment=&btitle=%E5%B0%84%E9%9B%95&pub_year=&pub_year__gt=&bread__gt=&bread__lt=
过滤器每个字段内部配置:
field_name: 过滤字段名,为对应模型中字段名
lookup_expr: 查询时所要进行的操作,是等值,范围、模糊匹配等
过滤器字段类型:
CharFilter 字符串类型
BooleanFilter 布尔类型
DateTimeFilter 日期时间类型
DateFilter 日期类型
DateRangeFilter 日期范围
TimeFilter 时间类型
NumberFilter 数值类型,对应模型中IntegerField, FloatField, DecimalField
来源:https://www.cnblogs.com/-wenli/p/13693356.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python爬取”顶点小说网“《纯阳剑尊》的示例代码
![](https://img.aspxhome.com/file/2023/4/105074_0s.png)
Python argparse模块应用实例解析
Python PyAutoGUI模块控制鼠标和键盘实现自动化任务详解
![](https://img.aspxhome.com/file/2023/9/107619_0s.png)
python实现LRU热点缓存及原理
基于python实现MUI区域滚动
![](https://img.aspxhome.com/file/2023/6/79396_0s.png)
Python免费验证码识别之ddddocr识别OCR自动库实现
![](https://img.aspxhome.com/file/2023/3/126913_0s.png)
原生JS封装_new函数实现new关键字的功能
![](https://img.aspxhome.com/file/2023/1/56041_0s.png)
30秒学会30个超实用Python代码片段【收藏版】
Python sorted函数详解(高级篇)
使用Eclipse如何开发python脚本
![](https://img.aspxhome.com/file/2023/8/68848_0s.jpg)
python pip如何手动安装二进制包
python如何通过psutil获取服务器cpu、内存、磁盘使用率
pandas读取Excel批量转换时间戳的实践
python里 super类的工作原理详解
python之从文件读取数据到list的实例讲解
python画微信表情符的实例代码
![](https://img.aspxhome.com/file/2023/9/78769_0s.png)
asp显示左边的n个字符自动识别汉字的函数
python频繁写入文件时提速的方法
Python 实现自动登录+点击+滑动验证功能
![](https://img.aspxhome.com/file/2023/1/118791_0s.jpg)