查询集可以在常规django中运行,但是将查询集应用于DRF序列化程序时却出现KeyError?

问题描述

我得到了以下查询集:

queryset = Expense.objects
.annotate(month=TruncMonth('expense_date'))
.values('month')
.annotate(total_cost=Sum('cost'))
.values('month','total_cost')
.order_by("month")

基本上将所有费用成本相加,然后按月将其分组。如果我只打印出查询集,它就可以正常工作:

<QuerySet [{'month': datetime.date(2020,9,1),'total_cost': Decimal('1029772.00')}]>

但是,如果我尝试对其进行序列化:

serializer = ExpenseSerializer(queryset,many=True)

我明白了

Got KeyError when attempting to get a value for field `cost` on serializer `ExpenseSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'cost'."

serializer.py

class ExpenseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Expense
        exclude = ("receipt",)

大惊小怪吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)