Where to change the form of json response in djang

2019-09-07 05:48发布

问题:

Lets say I have a model:

class MyModel(models.Model): 
    name = models.CharField(max_length=100)
    description= models.TextField()
    ...

Then I created ModelViewSet with HyperLinkedSerializer, so when I call my /api/mymodels endpint I get responses like this:

{
    "count": 2, 
    "next": null, 
    "previous": null, 
    "results": [
      { "name": "somename", "description": "desc"},
      { "name": "someothername", "description": "asdasd"},
    ]
}

and when I call /api/mymodels/1 I get:

{ "name": "somename", "description": "asdasd"}

but what I would like to get is:

{
    "metadata":{ ...}, 
    "results": { "name": "somename", "description": "desc"}
}

And I would like to use this format for all models at my website, so I dont want to change every viewset, I want to implement it in (most likely) one class and then use it for all my viewsets.

So my question is: which renderer or serializer or other class (Im really not sure) should I alter or create to get this behavior of json response?

回答1:

The first response appears to be a paginated response, which is determined by the pagination serializer. You can create a custom pagination serializer that will use a custom format. You are looking for something similar to the following:

class MetadataSerialier(pagination.BasePaginationSerializer):
    count = serializers.Field(source='paginator.count')
    next = NextPageField(source='*')
    previous = PreviousPageField(source='*')


class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    metadata = MetadataSerializer(source='*')

This should give you an output similar to the following:

{
    "metadata": {
        "count": 2, 
        "next": null, 
        "previous": null
    },
    "results": [
        { "name": "somename", "description": "desc"},
        { "name": "someothername", "description": "asdasd"}
    ]
}

The pagination serializer can be set globally through your settings, as described in the documentation.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_SERIALIZER_CLASS': {
        'full.path.to.CustomPaginationSerializer',
    }
}