Nesting fields in serialization with Django REST f

2019-05-23 00:47发布

Given that I have a model like this:

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)

I would like to group the client_* fields, so that the serialized JSON would look like this:

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

The following I tried, but doesn't work because client is not an actual field:

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')

What options do I have except for completely manual serialization? I prefer not to make a separate model for Client because this data really belongs in Case. Read-only is not good enough.

1条回答
狗以群分
2楼-- · 2019-05-23 01:03

You can try like this:

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
查看更多
登录 后发表回答