django-filter 使用Filter来筛选你的数据
django-filter##
Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model’s fields, displaying the form to let them do this.
这是一个用来筛选要显示数据集的工具,在上一篇的restframework中,这个应用也是可选的插件。所以这篇来看看这个app的应用。
文档:https://django-filter.readthedocs.org/en/latest/usage.html
安装:###
pip install django-filter'
接着把 'django_filters' 添加到 INSTALLED_APPS.
比如我们要使用filter来筛选上一篇中的项目post对象。
首先, 新建一个post/filters.py来保存我们的filter
import django_filters
from .models import Post
class PostFilter(django_filters.FilterSet):
class Meta:
model = Post
然后在views.py中添加对应的视图:
from .filters import PostFilter
...
def post_list(request):
f = PostFilter(request.GET, queryset=Post.objects.all())
return render(request, 'post/index.html', { 'filter':f })
建立视图模板文件templates/post/index.html
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter %}
{{ obj.title }} - {{ obj.content }} - ${{ obj.pub_date }}<br>
{% endfor %}
注意到这个模板中,用一个form来提交要filter的内容。然后结果显示在下面.
然后打开浏览器 localhost:8000/post/list
就可以看到这个了。
注意到我们的PostFilter并没有设置什么,那么就默认会把Post类的所有属性列出来。
如果我们只想筛选title, 那么在Meta类中添加fields属性:
class PostFilter(django_filters.FilterSet):
class Meta:
model = Post
fields = ['title']
但是title现在的匹配是区分大小写的,如果要改变这个特性,那么添加一个filter:
class PostFilter(django_filters.FilterSet):
title = django_filters.CharFilter(name='title', lookup_expr='iexact')
比如我们像筛选pub_date在某年之前:
publish_date_year_before = django_filters.NumberFilter(name='pub_date', lookup_expr='year__lt')
这样就会在页面显示publish date year before这个input了。
filter除了CharFilter, NumberFilter,还可以是MethodFilter
title = djang_filters.MethodFilter(name='title', action='my_custom_filter')
...
def my_custom_filter(self, queryset, value):
return queryset.filter(
title = value
)
要更详细参考文档。
最新文章
- JUnit备忘录
- Hadoop学习笔记1-如何简单布署hadoop
- Android设置按钮为透明
- aptana studio 3汉化方法 及支持jquery的方法
- Android FragmentActivity+viewpager的使用
- MySQL在windows和linux下的表名大小写问题
- Web应用架构的新趋势
- 分享:Python中的位运算符
- Java第5次实验提纲(集合)
- web服务器之nginx和apache的区别
- 在 Vim 中优雅地查找和替换(转)
- 关于node
- monkey_recorder录制monkeyrunner脚本
- 一切皆Socket
- springboot整合视图层之freemarker
- python包中__init__.py的作用
- [Oracle][Corruption]发生ORA00600[kdsgrp1]的时候,如何进行调查
- 第14月第11天 linkmap
- 页面可见性判断:document.hidden与visibilitychange事件
- 问题解决:在此页上的ActiveX控件
热门文章
- IOS 解析XML文档
- jquery serialize的使用
- 第8章 Android数据存储与IO——File存储
- LeetCode_Reverse Nodes in k-Group
- [置顶] tar命令-linux
- .net常考面试题
- strcat函数的坑点
- poj 1328 Radar Installation(贪心)
- [Redux] Extracting Container Components (FilterLink)
- Temporary ASP.NET Files 文件夹中保存的是什么内容?[转]