• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

230
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 2 months 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 2 months ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.