Search code examples
djangodjango-rest-framework

Got KeyError when attempting to get a value for field `date` on serializer


Im trying to do a queryset to show date__month and total of all 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']

However I get an error of

"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'."

Solution

  • Your querset does not return model objects but dictionaries with month and revenue as key, so you serialize with:

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

    and you plug in this serializer:

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

    beware that you can simplify the queryset to:

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