Django中按查询分组的KeyError

时间:2019-02-18 10:38:38

标签: python django django-rest-framework

我希望将具有共同数据并希望对资产负债表进行汇总的paper_quality,paper_size和paper_brand字段分组。

我尝试了使用自定义序列化程序的所有步骤。

class InwardDetails(models.Model):
paper_quality = models.ForeignKey(PaperType, on_delete=models.PROTECT)
paper_size = models.ForeignKey(PaperSize, on_delete=models.PROTECT)
paper_brand = models.ForeignKey(PaperBrand, on_delete=models.PROTECT)
thickness = models.CharField(max_length=100)
reams = models.IntegerField()
sheets = models.IntegerField()
job_card = models.CharField(max_length=100)
amount = models.IntegerField()
cost_per_sheet = models.IntegerField()
total_sheets = models.IntegerField()
balance_sheets = models.IntegerField(default=0)
account_access_key = models.ForeignKey(Ledger, null=True, blank=True, on_delete=models.PROTECT)

serializer.py类

class InventoryListSerializers(ModelSerializer):
class Meta:
    model = InwardDetails
    fields = ['paper_quality', 'paper_size', 'paper_brand', 'balance_sheets', 'thickness']

views.py

class GetListApiView(APIView):
def get(self, request):
    queryset = InwardDetails.objects.values('paper_quality',
                                            'paper_brand', 'paper_size').annotate(Sum('balance_sheets'))
    print(queryset)
    serializer = inward_inventory_serializers.InventoryListSerializers(queryset, many=True)
    return Response(serializer.data)

1 个答案:

答案 0 :(得分:0)

您好,欢迎在stackoverflow上!虽然没有错误堆栈跟踪,但是我只能猜测出确切的问题是什么,但是我可以看到查询集和序列化程序之间至少有两个问题。

第一个-由于您没有将Sum作为关键字参数提供给注释,因此它将以balance_sheets__sum的形式提供,而不是balance_sheets的形式。另外,将其设置为balance_sheets也是不可能的,因为它会与现有字段冲突-您可能应该在序列化程序上手动定义此字段。

第二个-您将.values限制为不选择序列化程序期望的thickness-因此可能出现KeyError。您可能需要一个专用的序列化器来进行聚合,例如:

class InventoryListSerializers(ModelSerializer):
    balance_sum = serializers.IntegerField(read_only=True)
    class Meta:
        model = InwardDetails
        fields = ['paper_quality', 'paper_size', 'paper_brand', 'balance_sum']

然后在您看来:

class GetListApiView(APIView):

    def get(self, request):
        queryset = InwardDetails.objects.values(
            'paper_quality','paper_brand', 'paper_size'
        ).annotate(balance_sum=Sum('balance_sheets'))
        print(queryset)
        serializer = inward_inventory_serializers.InventoryListSerializers(queryset, many=True)
        return Response(serializer.data)