我正在尝试使用类似于Django Admin中的过滤器功能实现ListView。 我查看了django-filter,但不清楚如何在模板上使用它。
这是我的ListView:
@method_decorator(login_required, name='dispatch')
class ListProjects(ListView):
model = Project
paginate_by = 100
list_filter=('start_dt','end_dt','status')
在这种情况下,我想按这三个字段进行过滤。
答案 0 :(得分:0)
Django管理过滤器通过根据根据所选过滤器传递的GET参数过滤查询集来工作。话虽如此,您可以通过覆盖get_queryset
的{{1}}方法并执行类似的操作来轻松实现相同的目的:
ListView
现在,您可以在模板中使用def get_queryset(self):
qs = super().get_queryset()
get_params = self.request.GET.dict()
# search
if get_params.get('q') and hasattr(self, 'search_fields'):
# logic for search goes here....
# filter
if hasattr(self, 'list_filter'):
filter_fields = self.list_filter
for key, value in get_params.items():
if key in filter_fields and key != 'q' and value != '':
qs = qs.filter(**{key:value})
return qs
标签来呈现过滤器的选择,就像在admin中一样。使用此方法时,请确保保留获取参数。
希望这会有所帮助。
答案 1 :(得分:0)
因此,我在自定义视图和管理员之间进行了混合。这是最终的解决方案:
class ListProjects(ListView):
model = Project
paginate_by = 100
adm_model = ProjectAdmin(Project,AdminSite())
changelist = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
self.changelist = self.adm_model.get_changelist_instance(self.request)
context['cl']=self.changelist
return context
def get_queryset(self):
qs = super().get_queryset()
get_params = self.request.GET.dict()
self.changelist = self.adm_model.get_changelist_instance(self.request)
(self.changelist.filter_specs, self.changelist.has_filters, remaining_lookup_params,
filters_use_distinct) = self.changelist.get_filters(self.request)
# Then, we let every list filter modify the queryset to its liking.
qs = self.changelist.root_queryset
for filter_spec in self.changelist.filter_specs:
new_qs = filter_spec.queryset(self.request, qs)
if new_qs is not None:
qs = new_qs
try:
qs = qs.filter(**remaining_lookup_params)
except:
pass
# Set ordering.
ordering = self.changelist.get_ordering(self.request, qs)
qs = qs.order_by(*ordering)
# Apply search results
qs, search_use_distinct = self.changelist.model_admin.get_search_results(self.request, qs, self.changelist.query)
return qs
在模板中,我有搜索件
<div class="row-fluid">
<div class="span12">
<form class='form-inline' accept-charset='UTF-8' method='get' action=''>
<input type="text" size="40" name="q" value = "{{cl.params.q}}" id="searchbar" autofocus="">
<button type='submit' class="btn">Search</button>
</form>
</div>
</div>
过滤片
{% if cl.has_filters %}
<div id="changelist-filter">
<h3>{% trans 'Filter' %}</h3>
{% for spec in cl.filter_specs %}
{% admin_list_filter cl spec %}
</div>
{% endfor %}
</div>
{% endif %}