从get_queryset () django中更新上下文参数值



我的代码是

class Leads(LoginRequiredMixin, ListView):
def get_queryset(self):
q = self.request.GET.get('q', "all")
        if q == "customer":
            qs = alllead.objects.filter(isCustomer="yes")
        elif q == "lead":
            qs = alllead.objects.filter(isCustomer="no")
        else:
            qs = self.queryset
return qs
def get_context_data(self, **kwargs):
    context = super(Leads, self).get_context_data(**kwargs)
    count = self.queryset.count()
    context['count'] = count or "000"
return context

所以我过滤我的查询集,我还需要设置记录计数作为上下文参数"计数"但是记录的数量没有更新所以我把代码改成

def get_queryset(self):
q = self.request.GET.get('q', "all")
        if q == "customer":
            qs = alllead.objects.filter(isCustomer="yes")
        elif q == "lead":
            qs = alllead.objects.filter(isCustomer="no")
        else:
            qs = self.queryset
return qs
def get_context_data(self, **kwargs):
    context = super(Leads, self).get_context_data(**kwargs)
     q = self.request.GET.get('q', "none")
     if q == "customer":
         count = alllead.objects.filter(isCustomer="yes").count()
     elif q == "lead":
         count = alllead.objects.filter(isCustomer="no").count()
     else:
         count = self.queryset.count()
     context['count'] = count or "000"
return context

我认为我在复制代码,这不是正确的方式去做。谁能告诉我更新

的最佳方法?
context['count'] = qs.count()
#inside get_queryset()

一旦调用了超类get_queryset(),那么qs将作为alllead_list添加到上下文中;你可以从那里访问它

def get_context_data(self, **kwargs):
    context = super(Leads, self).get_context_data(**kwargs)
    count = context['alllead_list'].count()

然而,我认为你根本不需要在视图中这样做;您可以通过访问{{ allead_list.count|default:"000" }}在模板中轻松地完成此操作。

编辑由于查询集是分页的,您可以直接从分页器获得计数:context['paginator'].count或在模板{{ paginator.count }}中。

相关内容

  • 没有找到相关文章

最新更新