惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
WordPress大学
WordPress大学
Recent Announcements
Recent Announcements
G
Google Developers Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Check Point Blog
J
Java Code Geeks
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
量子位
A
About on SuperTechFans
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

郑文峰的博客

使用dify对接飞书多维表格 使用n8n对接飞书多维表格 服务启动时出现 OOM 一次服务升级时pg表DDL执行超时失败 Go语言高效IO缓冲技术详解 Go语言延迟初始化(Lazy Initialization)最佳实践 Go语言字符串拼接性能对比与优化指南 Go语言结构体内存对齐完全指南 Go语言空结构体:零内存消耗的高效编程 Go语言堆栈分配与逃逸分析深度解析 Go语言原子操作完全指南 Go语言内存预分配完全指南 Go语言不可变数据共享:无锁并发编程实践 Go语言零拷贝技术完全指南 Go语言遍历性能深度解析:从原理到优化实践 Go语言Interface Boxing原理与性能优化指南 Go协程池深度解析:原理、实现与最佳实践 使用etcd分布式锁导致的协程泄露与死锁问题 基于pre-commit的Python代码规范落地实践 初识 MCP Server pulsar阻塞导致logstash无法接入日志 django-prometheus使用及源码分析 kube-proxy源码分析 kubernetes service如何通过iptables转发 tcp缓存引起的日志丢失 django-apschedule定时任务异常停止 理解calico容器网络通信方案原理 理解flannel的三种容器网络方案原理 理解Linux IPIP隧道 理解VXLAN网络
django Filtering 使用
zhengwenfeng · 2022-08-10 · via 郑文峰的博客

# 简介

django-filter是单独的一个库,不属于djangorestframework中的,属于外部库引用进来使用。下面就来介绍下filter

有三种filter方式:

  1. DjangoFilterBackend
  2. SearchFilter
  3. OrderingFilter

# 准备工作

首先需要安装django-filter

pip install django-filter

然后需要将django_filters 添加到 INSTALLED_APPS中

INSTALLED_APPS = [
    'django_filters',
]

1
2
3

# DjangoFilterBackend

# 使用默认的过滤

在View中添加filter_backends属性,设置过滤方式DjangoFilterBackend,并且设置过滤的属性。


from django_filters.rest_framework import DjangoFilterBackend

class GoodsListViewSet(ModelViewSet):    
    queryset = Goods.objects.all()    
    serializer_class = GoodsSerializer    
    pagination_class = MyPagination    
    filter_backends = (DjangoFilterBackend,)    
    filterset_fields = ('name', 'shop_price')

1
2
3
4
5
6
7
8
9

在调试界面中会出现过滤器选项, 可以在其中过滤nameshop_price两个属性的值 在这里插入图片描述 在这里插入图片描述

# 自定义过滤

创建filters.py,在里面定义自己的过滤器。 可以通过最小的价格、最大的价格,和模糊查询名字去过滤想要的数据。

from django_filters import FilterSet, NumberFilter, CharFilter
from .models import Goods

class GoodsFilter(FilterSet):   
    """    商品的过滤类    """    
    price_min = NumberFilter(field_name='shop_price', help_text="最低价格", lookup_expr='gte')    
    price_max = NumberFilter(field_name='shop_price', lookup_expr='lte')    
    name = CharFilter(field_name='name', lookup_expr="icontains")    
    class Meta:        
        model = Goods        
        fields = ['price_min', 'price_max', 'name']

1
2
3
4
5
6
7
8
9
10
11

将该过滤器添加到view中 view.py

class GoodsListViewSet(ModelViewSet):    
    queryset = Goods.objects.all()    
    serializer_class = GoodsSerializer   
    pagination_class = MyPagination    
    filter_backends = (DjangoFilterBackend,)    
    filter_class = GoodsFilter

1
2
3
4
5
6

最后可以通过 http://127.0.0.1:8000/goods/?price_min=150&price_max=160&name=水果 去过滤得到想要的数据。

# SearchFilter

这个Filter是基于Django的搜索。现在我们将SearchFilter集成到过滤里面来。在filter_backends中添加SearchFiler,然后再在search_fields中添加需要搜索的字段即可,在搜索的字段前面字符变量来提高搜索效率。

  • '^' Starts-with search.
  • '=' Exact matches.
  • '@' Full-text search. (Currently only supported Django's MySQL backend.)
  • '$' Regex search.

view.py

from rest_framework.filters import SearchFilter

class GoodsListViewSet(ModelViewSet):    
    queryset = Goods.objects.all()    
    serializer_class = GoodsSerializer    
    pagination_class = MyPagination    
    filter_backends = (DjangoFilterBackend, SearchFilter)    
    filter_class = GoodsFilter    
    search_fields = ("=name", 'goods_brief', 'goods_desc')

1
2
3
4
5
6
7
8
9

# OrderingFilter

可以对数据进行排序筛选数据。我们将其加入进去

view.py

from rest_framework.filters import SearchFilter, OrderingFilter



class GoodsListViewSet(ModelViewSet):    
    queryset = Goods.objects.all()    
    serializer_class = GoodsSerializer    
    pagination_class = MyPagination    
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) 
    filter_class = GoodsFilter    
    search_fields = ("=name", 'goods_brief', 'goods_desc')
    ordering_fields = ("sold_num", "add_time")

1
2
3
4
5
6
7
8
9
10
11
12
13

# 自定义过滤条件

修改filters.py文件,编写过滤方法top_category_filter绑定到top_category字段中,即可通过该属性名进行相应的筛选。

class GoodsFilter(FilterSet):    
    """    商品的过滤类    """    
    pricemin = NumberFilter(field_name='shop_price', help_text="最低价格", lookup_expr='gte')    
    pricemax = NumberFilter(field_name='shop_price', lookup_expr='lte')    
    name = CharFilter(field_name='name', lookup_expr="icontains")   
    top_category = NumberFilter(method='top_category_filter')    
    
    def top_category_filter(self, queryset, name, value):        
        return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | (category__parent_category__parent_category_id=value))
    
    class Meta:        
        model = Goods
        fields = ['pricemin', 'pricemax', 'name']

1
2
3
4
5
6
7
8
9
10
11
12
13
14