Simple example of how to use a class based view and django-filter?

别说谁变了你拦得住时间么 提交于 2019-12-01 16:52:04

问题


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})

回答1:


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.

I added the contents of list.py into my main app as main_app/filter_mixin.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']

Now the view.py becomes:

from vanilla import ListView

from .filter import ContactFilter
from galleria.filter_mixin import ListFilteredMixin


class ContactList(ListFilteredMixin, ListView):
    filter_set = ContactFilter



回答2:


As mentioned in the link Viewing subsets of objects

You can use something like this is your views.py

class modelListView(someGenericView): queryset = modelName.object.filter(myFilter)



来源:https://stackoverflow.com/questions/24305854/simple-example-of-how-to-use-a-class-based-view-and-django-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!