如何计算不同查询集中的匹配项

在对所有模型进行搜索后,我想在我的模板中计算不同的查询集,但似乎不同的查询集位于列表列表中。


我的视图功能:


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>


回首忆惘然
浏览 68回答 1
1回答

泛舟湖上清波郎朗

好吧,我找到了解决这个问题的方法。我在上下文字典中再次插入object_list:def get_context_data(self,*args,**kwargs):&nbsp; &nbsp; &nbsp; &nbsp; context=super().get_context_data(*args,**kwargs)&nbsp; &nbsp; &nbsp; &nbsp; c=context['object_list']&nbsp; &nbsp; &nbsp; &nbsp; cname=[l.model.__name__ for l in c]&nbsp; &nbsp; &nbsp; &nbsp; for l in zip(cname,c):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context[l[0].lower()]=l[1]&nbsp; &nbsp; &nbsp; &nbsp; return context这不是最优雅的解决方案,如果其他人有其他解决方案,请分享。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python