You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DRF查询月度营收时出现KeyError: 'date'错误求助

问题解决方法

错误原因

你的查询集通过values('month')和聚合操作后,返回的是包含month(月份)和revenue(销售额总和)的字典集合,但你的RevenueSerializer却声明要序列化date和sale_price字段——这两个字段在聚合后的查询结果里根本不存在,所以触发了KeyError。

修复步骤

1. 调整序列化器匹配查询结果字段

因为现在返回的是聚合后的统计数据,而非Transactions模型的原始实例,推荐直接用Serializer定义对应字段:

from rest_framework import serializers

class RevenueSerializer(serializers.Serializer):
    month = serializers.IntegerField()
    # 根据你的sale_price字段实际类型调整DecimalField的参数(比如max_digits、decimal_places)
    revenue = serializers.DecimalField(max_digits=12, decimal_places=2)

如果坚持使用ModelSerializer,也可以手动添加聚合字段的定义,并修改fields列表:

class RevenueSerializer(serializers.ModelSerializer):
    month = serializers.IntegerField()
    revenue = serializers.DecimalField(max_digits=12, decimal_places=2)

    class Meta:
        model = Transactions
        fields = ['month', 'revenue']

2. 确认查询集的依赖导入

确保已经导入需要的聚合函数和数据库函数:

from django.db.models import Sum
from django.db.models.functions import ExtractMonth

验证修改

调整后,查询集返回的month和revenue字段会被序列化器正确处理,不会再出现KeyError。

内容的提问来源于stack exchange,提问作者ElasticPanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:24:53