如何使用基于类的视图和django-filter的简单示例? [英] Simple example of how to use a class based view and django-filter?

查看:88
本文介绍了如何使用基于类的视图和django-filter的简单示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档中的示例 https://django-filter.readthedocs。 org / en / latest / usage.html ,我认为是基于函数的视图。我目前正在研究如何使用基于类的视图来做到这一点。

The example in the documentation, https://django-filter.readthedocs.org/en/latest/usage.html, is I think for a function based view. I am currently researching how to do this with a class based view.

def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
return render_to_response('my_app/template.html', {'filter': f})


推荐答案

多了一些挖掘工作,我已经设法解决了。我从这里使用了代码 https://github.com/rasca/django-enhanced-cbv

A bit more digging and I have managed to answer it. I have used the code from here https://github.com/rasca/django-enhanced-cbv.

我将 list.py 的内容添加为我的主应用程序,作为 main_app / filter_mixin.py

I added the contents of list.py into my main app as main_app/filter_mixin.py

然后在应用程序中,我向列表视图添加了搜索,我添加了文件 filter.py 像这样(与文档相同)

Then in the app I was adding a search to the list view I added the file filter.py like this (identical to documentation)

from django_filters import FilterSet
from .models import Contact


class ContactFilter(FilterSet):
    class Meta:
        model = Contact
        fields = ['name_first', 'name_last']

现在 view.py 变为:

from vanilla import ListView

from .filter import ContactFilter
from galleria.filter_mixin import ListFilteredMixin


class ContactList(ListFilteredMixin, ListView):
    filter_set = ContactFilter

这篇关于如何使用基于类的视图和django-filter的简单示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆