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

        )

要更详细参考文档。

转载于:https://www.cnblogs.com/wenning/p/5424745.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值