我想在使用 DRF 发回 JSON 响应之前执行一些数据操作。
情况
我的模型是:
class ThirdParty(models.Model):
label = models.CharField(verbose_name=_("Third party label"), null=False, blank=False, default=DEFAUT_LABEL, max_length=255)
class CashFlow(TimeStampedModel):
date = models.DateField(verbose_name=_("Due date"), null=True, blank=True)
forecasted_value = models.DecimalField(verbose_name=_("Forecasted value"), null=True, blank=True, max_digits=11, decimal_places=2)
third_party = models.ForeignKey(ThirdParty, null=False, blank=False, related_name='cashflows')
目前我有两个序列化程序:
class CashFlowSerializer(serializers.ModelSerializer):
third_party = serializers.PrimaryKeyRelatedField(many=False, read_only=True, allow_null=True)
class Meta:
model = CashFlow
fields = ('id', 'date', 'forecasted_value', 'edited_value', 'third_party')
class ThirdPartyReadSerializer(serializers.ModelSerializer):
cashflows = CashFlowSerializer(many=True, read_only=True)
class Meta:
model = ThirdParty
fields = ('id', 'label', 'category', 'cashflows',)
我的第三方 View 正确地返回了一个不错的 JSON:
{
"id": 15,
"label": "Adeo",
"category": 7,
"cashflows": [
{
"id": 1,
"date": "2016-11-01",
"forecasted_value": "2000.00",
"edited_value": null,
"third_party": 15
},
{
"id": 2,
"date": "2017-01-17",
"forecasted_value": "3000.00",
"edited_value": null,
"third_party": 15
},
{
"id": 3,
"date": "2017-01-31",
"forecasted_value": "1000.00",
"edited_value": null,
"third_party": 15
}
]
}
问题
我想按月对现金流进行分组并添加它们的值。
问题是:最好的方法是什么?
预期的结果是:
{
"id": 15,
"label": "Adeo",
"category": 7,
"cashflows": [
{
"date": "2016-11-01",
"forecasted_value": "2000.00",
"edited_value": null,
"third_party": 15
},
{
"date": "2017-01-01",
"forecasted_value": "4000.00",
"third_party": 15
}
]
}
这将是一个只读序列化程序。
最佳答案
使用序列化程序的 to_representation :
def to_representation(self, obj):
data = super().to_representation(obj)
# manipulate data['cashflows'] to group by month
return data
关于django - 如何编写自定义序列化程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40747927/