簡體   English   中英

如何在Django rest框架中進行分組和計數

[英]How to do Group by and count in Django rest framework

我在用

Django==1.10.6
djangorestframework==3.6.2

到目前為止,我已經嘗試過,但是出現關鍵錯誤

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__'

錯誤,我在/ sales-report /處得到KeyError,“嘗試在序列化程序SalesReportSerializer上獲取字段quantity的值時,得到了SalesReportSerializer 。\\ n序列化程序字段的名稱可能不正確,並且與dict實例上的任何屬性或鍵都不匹配。\\ n原始異常文字是:“數量”。

您的queryset錯誤。 現在甚至都不是queryset:

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': ...}, ...]

因此,方法“ get_queryset”的結果是沒有字段quantity的dict。 序列化器會告訴您有關錯誤的信息。

嘗試將序列化程序所需的所有值添加到最后一個values調用中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM