2
我想在使用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',)
我的第三方觀點是正確返回一個不錯的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
}
]
}
這將是一個只讀序列化。
感謝,這讓我這個黃金SO張貼http://stackoverflow.com/questions/8746014/django-group-by-date-day-month-year – bixente57