2017-04-17 21 views
0

我使用如何通過做集團在Django的REST框架算

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

錯誤我在/銷售報告/「得到KeyError異常得到KeyError異常時 試圖在串行 SalesReportSerializer得到一個值字段quantity。\ n串行器字段可能錯誤地命名爲 ,並且不匹配dict 實例上的任何屬性或密鑰。\ n原始異常文本爲:'quantity'。

回答

0

您的查詢集錯了。它甚至不是現在的查詢集:

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的字典。串行器告訴你有關錯誤。

嘗試添加串行器所需的所有值,以調用values

+0

仍然沒有工作, 數據=(imodels.Sales.objects .annotate(月= TruncMonth( '日期')) .values( '月') .annotate(C = SUM( '數量')) 返回數據 現在的錯誤是 'int(')','''','''''' '對象沒有屬性'PK' –