使用Django REST框架将字段嵌套在序列化中

时间:2014-10-06 14:11:25

标签: django django-rest-framework

鉴于我有这样的模型:

class Case(models.Model):
    opened = models.DateTimeField(auto_now_add=True)
    client_first_name = models.CharField(max_length=50)
    client_last_name = models.CharField(max_length=50)

我想对client_*字段进行分组,以便序列化的JSON看起来像这样:

{
    "opened": "2014-10-05T19:30:48.667Z",
    "client": {
        "first_name": "John",
        "last_name": "Doe"
    }
}

以下我尝试了,但由于client不是实际字段而无法工作:

class ClientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Case
        fields = ('client_first_name', 'client_last_name')


class CaseSerializer(serializers.ModelSerializer):
    client = ClientSerializer()

    class Meta:
        model = Case
        fields = ('opened', 'client')

除完全手动序列化外,我还有哪些选项?我不想为Client创建单独的模型,因为此数据确实属于Case。只读是不够好的。

1 个答案:

答案 0 :(得分:1)

您可以尝试这样:

class CaseSerializer(serializers.ModelSerializer):
    client = serializers.SerializerMethodField('client')

    class Meta:
        model = Case
        fields = ('opened', 'client')

    def client(self, obj):
        client_fields = {}
        client_fields['first_name'] = obj.client_first_name
        client_fields['last_name'] = obj.client_last_name
        return client_fields