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
)
要更詳細參考文檔。