代码之家  ›  专栏  ›  技术社区  ›  ElasticPanda

尝试获取序列化程序上字段“date”的值时发生KeyError

  •  0
  • ElasticPanda  · 技术社区  · 10 月前

    我试图做一个查询集来显示日期__月和所有sale_prices的总和

    class RevenueChartListView(ListAPIView):
        queryset = Transactions.objects.annotate(month=ExtractMonth('date')).values('month').annotate(revenue=Sum('sale_price')).order_by('month')
        serializer_class = RevenueSerializer
    
    class RevenueSerializer(serializers.ModelSerializer):
        class Meta:
            model = Transactions
            fields = ['date', 'sale_price']
    

    然而,我犯了一个错误

    "Got KeyError when attempting to get a value for field `date` on serializer `RevenueSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'date'."
    
    1 回复  |  直到 10 月前
        1
  •  0
  •   willeM_ Van Onsem    10 月前

    你的问题集确实如此 返回模型对象,但字典 month revenue 作为key,因此您可以序列化为:

    class RevenueChartSerializer(serializers.Serializer):
        month = models.IntegerField()
        revenue = models.IntegerField()  # or perhaps a FloatField?

    然后插入此串行器:

    class RevenueChartListView(ListAPIView):
        queryset = (
            Transactions.objects.annotate(month=ExtractMonth('date'))
            .values('month')
            .annotate(revenue=Sum('sale_price'))
            .order_by('month')
        )
        serializer_class = RevenueChartSerializer

    请注意,您可以将查询集简化为:

    class RevenueChartListView(ListAPIView):
        queryset = (
            Transactions.objects.values(month=ExtractMonth('date'))
            .annotate(revenue=Sum('sale_price'))
            .order_by('month')
        )
        serializer_class = RevenueChartSerializer