[英]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.