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  )

要更详细参考文档。

最新文章

  1. JUnit备忘录
  2. Hadoop学习笔记1-如何简单布署hadoop
  3. Android设置按钮为透明
  4. aptana studio 3汉化方法 及支持jquery的方法
  5. Android FragmentActivity+viewpager的使用
  6. MySQL在windows和linux下的表名大小写问题
  7. Web应用架构的新趋势
  8. 分享:Python中的位运算符
  9. Java第5次实验提纲(集合)
  10. web服务器之nginx和apache的区别
  11. 在 Vim 中优雅地查找和替换(转)
  12. 关于node
  13. monkey_recorder录制monkeyrunner脚本
  14. 一切皆Socket
  15. springboot整合视图层之freemarker
  16. python包中__init__.py的作用
  17. [Oracle][Corruption]发生ORA00600[kdsgrp1]的时候,如何进行调查
  18. 第14月第11天 linkmap
  19. 页面可见性判断:document.hidden与visibilitychange事件
  20. 问题解决:在此页上的ActiveX控件

热门文章

  1. IOS 解析XML文档
  2. jquery serialize的使用
  3. 第8章 Android数据存储与IO——File存储
  4. LeetCode_Reverse Nodes in k-Group
  5. [置顶] tar命令-linux
  6. .net常考面试题
  7. strcat函数的坑点
  8. poj 1328 Radar Installation(贪心)
  9. [Redux] Extracting Container Components (FilterLink)
  10. Temporary ASP.NET Files 文件夹中保存的是什么内容?[转]