Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

713
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda