Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

712
Views
How to do Group by and count in Django rest framework

I am using

Django==1.10.6
djangorestframework==3.6.2

I have tried so far but i am getting key error

views.py

from django.db.models import Func, F, Sum, Count
from django.db.models.functions import TruncMonth

class SalesReportViewSet(viewsets.ModelViewSet):
    queryset = imodels.Sales.objects.all()
    serializer_class = iserializers.SalesReportSerializer

    def get_queryset(self):
        data = imodels.Sales.objects.annotate(month=TruncMonth('date')).values('month').annotate(c=Count('id')).values('month', 'c')
        return data

models.py

class Sales(models.Model):

    orig_quantity = 0

    product = models.ForeignKey(Product)
    sold_to = models.ForeignKey(Merchant)
    quantity = models.PositiveIntegerField()
    desc = models.CharField(max_length=255)
    date = models.DateTimeField()
    created_at = models.DateTimeField(default=datetime.now)

serializers.py

class SalesReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Sales
        #fields = ['id', 'quantity', 'total']
        fields = '__all__'

error i am getting KeyError at /sales-report/ "Got KeyError when attempting to get a value for field quantity on serializer SalesReportSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'quantity'.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your queryset is wrong. It is not even queryset now:

data = (imodels.Sales.objects
        .annotate(month=TruncMonth('date'))
        .values('month')
        .annotate(c=Count('id'))
        .values('month', 'c')  # After this call you will receive list of dicts
                               # [{"month": ..., 'c': ...}, ...]

So result of your method 'get_queryset' is a dict that does not have field quantity. Serializer tells you about that in error.

Try add all values that are required by serializer to last values call.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!