我的代码是
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
所以我正在过滤我的查询集,我还需要将记录计数设置为上下文参数“count” 但记录的数量没有更新 所以我把我的代码改为
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()
答案 0 :(得分:0)
调用超类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 }}
获取计数。