简体   繁体   中英

update context parameter value from get_queryset () django

my code is

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

so i am filtering my queryset and also i need to set record count as context parameter "count" but the number of record is not updating so i have changed my code to

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

i think i am duplicating code and this is not the proper way to do it. can anyone suggest me the optimal way to update

context['count'] = qs.count()
#inside get_queryset()

Once you've called the superclass get_queryset() , then the qs is added to the context as alllead_list ; you can just access it from there.

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

However, I don't think you need to do this in the view at all; you can just as easily do this in the template by accessing {{ allead_list.count|default:"000" }} .

Edit Since the queryset is paginated, you can get the count directly from the paginator: context['paginator'].count or in the template {{ paginator.count }} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM