在对所有模型进行搜索后,我想在我的模板中计算不同的查询集,但似乎不同的查询集位于列表列表中。
我的视图功能:
class Search(ListView):
template_name='artdb/searchResult.html'
def get_queryset(self): # override get_queryset() has to have that name...
q=self.request.GET.get('seastr')
models=[Person,Activity,Member,Comment]
fields=[l._meta.fields for l in models]
res=[]
for i,j in enumerate(models):
sq=[Q(**{x.name + "__icontains" : q}) for x in fields[i] if not isinstance(x,ForeignKey)]
res+=[j.objects.filter(k) or None for k in sq]
res=[k for k in res if k]
if q:
return res
else:
return Person.objects.none() # SELECT ... WHERE headline ILIKE '%Lennon%';
def get_context_data(self,*args,**kwargs):
#q=self.request.GET.get('seastr')
context=super().get_context_data(*args,**kwargs)
context['member']=Member.objects.all()
return context
上下文字典:
{'page_obj': None, 'view': <artdb.views.Search object at 0x7f415ec88080>, 'is_paginated': False, 'object_list': [<QuerySet [<Person: David Bolander>, <Person: adam something>]>, <QuerySet [<Comment: david bolander comment>]>], 'member': <QuerySet [<Member: 2019-11-21>, <Member: 2020-02-10>]>, 'paginator': None}
我的模板:
{% extends "artdb/index.html" %}
{% block sr1 %}
<ul>
<a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
Persons: {{object_list.count}}
</a>
<a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
Activities: {{activity.count}}
</a>
<a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
Members: {{member.count}}
</a>
<a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
Comments: {{comment.count}}
</a>
<br></br>
</ul>
{% endblock sr1 %
从模板中可以看出,我想对标记中的匹配项进行计数,但查询集在上下文字典中堆叠为列表列表。例如,可以对成员进行计数,因为它是稍后添加的,并且不在列表列表中。我该如何解决这个问题?<a>
泛舟湖上清波郎朗
相关分类