在对所有模型进行搜索后,我想在我的模板中计算不同的查询集,但似乎不同的查询集位于列表列表中。我的视图功能: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>
1 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
好吧,我找到了解决这个问题的方法。我在上下文字典中再次插入object_list:
def get_context_data(self,*args,**kwargs):
context=super().get_context_data(*args,**kwargs)
c=context['object_list']
cname=[l.model.__name__ for l in c]
for l in zip(cname,c):
context[l[0].lower()]=l[1]
return context
这不是最优雅的解决方案,如果其他人有其他解决方案,请分享。
添加回答
举报
0/150
提交
取消