如何编写自定义序列化程序?

时间:2016-11-22 17:20:02

标签: django serialization django-rest-framework

我想在使用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',)

我的ThirdParty视图正确地返回了一个漂亮的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
            }
        ]
    }

这将是一个只读序列化器。

1 个答案:

答案 0 :(得分:7)

使用序列化程序to_representation

def to_representation(self, obj):
    data = super().to_representation(obj)
    # manipulate data['cashflows'] to group by month
    return data