问题描述
文档中的示例,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
然后在应用程序中,我将搜索添加到列表视图中,我添加了这样的文件 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 的简单示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!