Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading