zoukankan      html  css  js  c++  java
  • 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
    
            )
    
    

    要更详细参考文档。

  • 相关阅读:
    【代码审计】XDCMS 报错注入
    【渗透测试】MS17-010 "永恒之蓝" 修复方案
    【代码审计】MenInfo文件包含漏洞
    【代码总结】数据库抽象层PDO
    【代码总结】PHP面向对象之接口与多态性应用
    【代码总结】PHP面向对象之抽象类
    东哥手把手带你刷二叉树(第一期)
    二叉树的序列化,就那几个框架,枯燥至极
    二叉堆详解实现优先级队列
    递归反转链表的一部分
  • 原文地址:https://www.cnblogs.com/wenning/p/5424745.html
Copyright © 2011-2022 走看看