我有一个过滤器:
class BookFilter(django_filters.FilterSet):
class Meta:
model = Book
fields = '__all__'
和一个ListView查看结果:
class SearchResultsListView(ListView):
model = Book
context_object_name = 'book_list'
template_name = 'book/search_results.html'
我想拥有一个搜索表单,您可以在其中根据课程的所有字段(例如,由X撰写的所有书籍,超过3星,进行过滤)。
如何将表单传递给模型,以及如何使用get请求根据需要使用django-filter进行过滤?
我正在使用Django 3.0和django-filter 2.2.0
我认为django-filter部分下的Generic view & configuration文档中的所有内容都已很好地记录在案。django_filters.views.FilterView
类类似于Django的ListView
,您可以使用它来过滤结果。
from django_filters.views import FilterView
class SearchResultsListView(FilterView):
model = Book
context_object_name = 'book_list'
template_name = 'book/search_results.html'
并在您的[[book/search_results.html
模板中进行一些更改,更改为mentioned in here,
{% extends "base.html" %}
{% block content %}
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter.qs %}
{{ obj.name }} - ${{ obj.price }}<br />
{% endfor %}
{% endblock %}