Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

718
Visualizações
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'.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda