This is the query I am running to get Total Sales for each party.
Party.objects.annotate(total_sales=Sum('sales__salestransaction__total_cost'))
It shows correct results. But when I try to apply in my view with get_queryset, it is not working and shows a FieldError which is:
Cannot resolve keyword 'total_sales' into field. Choices are: party_address, party_id, party_name, party_phone, sales
My View
class PartyListView(ListView):
paginate_by = 2
model = Party
template_name = 'mael/parties.html'
def querystring(self):
qs = self.request.GET.copy()
qs.pop(self.page_kwarg, None)
return qs.urlencode()
def get_queryset(self):
qs = super().get_queryset()
if 'q' in self.request.GET:
search_txt = self.request.GET['q']
qs = qs.filter(party_name__icontains=search_txt).annotate(total_sales=Sum('sales__salestransaction__total_cost'))
return qs.order_by('total_sales')
def get(self, request):
form = PartyForm()
party_list = self.get_queryset()
qrstring = self.querystring()
paginator = Paginator(party_list, 5)
page_number = request.GET.get('page')
party_list = paginator.get_page(page_number)
return render(request, self.template_name, {'form': form, 'party_list': party_list, 'querystring': qrstring})
Models
class Party(models.Model):
party_id = models.BigAutoField(primary_key=True)
party_name = models.CharField(max_length=128)
party_phone = models.CharField(max_length=128)
party_address = models.CharField(max_length=128)
def __str__(self):
return self.party_name
class Sales(models.Model):
invoice_no = models.BigAutoField(primary_key=True)
invoice_date = models.DateField(default=date.today)
party = models.ForeignKey(Party, on_delete=models.CASCADE)
def __str__(self):
return str(self.invoice_no)
class SalesTransaction(models.Model):
sales = models.ForeignKey(Sales, on_delete=models.CASCADE)
item_qty = models.PositiveIntegerField(default=0)
total_cost = models.PositiveIntegerField(default=0)
def __str__(self):
return self.item_name
What is a problem with the get_queryset function and how can I solve this error? Please help.
CodePudding user response:
You can not .order_by('total_sales')
in case the if 'q' in self.request.GET
returns False
, you thus should annotate in both cases:
def get_queryset(self):
qs = super().get_queryset().annotate(
total_sales=Sum('sales__salestransaction__total_cost')
)
if 'q' in self.request.GET:
search_txt = self.request.GET['q']
qs = qs.filter(party_name__icontains=search_txt)
return qs.order_by('total_sales')