经过过滤后,我得到以下结果:
[{SV2: "2*3"},{SV2: "3*4"},{SV2: "50"},{RV2: "10"},{RV2: "7*5"},{RV2: "50"}]
但是我想让所有对象具有与一个数组相同的键:
[{SV2: ["2*3","3*4","50"]},{RV2: ["10","7*5","50"]}]
在将信息发送到前端之前,如何在视图/序列化器中执行此操作?
型号:
class ProcessedStockAmounts(models.Model):
prodName = models.ForeignKey(Productlist, on_delete=models.CASCADE, blank=False, unique=False, related_name='prod')
amount = models.CharField(unique=True, max_length=255)
time = models.ForeignKey(StockTakingTimes, on_delete=models.CASCADE, blank=False, unique=False, default=1)
序列化器:
class ProcessedStockSerializer(serializers.ModelSerializer):
slug_field='productid', required=False)
name = serializers.CharField(source='prodName')
class Meta:
model = ProcessedStockAmounts
fields = '__all__'
def to_representation(self, instance):
result = super(ProcessedStockSerializer, self).to_representation(instance)
new_result = {result['name']: result['amount']}
return new_result
查看:
class ProcessedStockTimeView(generics.ListCreateAPIView):
serializer_class = ProcessedStockSerializer
def get_queryset(self):
time = self.kwargs['stock']
value = ProcessedStockAmounts.objects.filter(time__times__icontains=time)
return value