在Django Rest框架中哪里更改JSON响应的形式? [英] Where to change the form of json response in django rest framework?

查看:64
本文介绍了在Django Rest框架中哪里更改JSON响应的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个模型:

Lets say I have a model:

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

然后我使用HyperLinkedSerializer创建了ModelViewSet,所以当我调用/ api / mymodels endpint时,会得到如下响应:

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"},
    ]
}

,当我呼叫/ api / mymodels / 1时,我得到:

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

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

,但我想得到的是:

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

我会ike可以在我的网站上对所有模型使用这种格式,所以我不想更改每个视图集,我想在(最有可能的)一个类中实现它,然后将其用于我的所有视图集。

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.

所以我的问题是:我应该更改或创建哪个渲染器,序列化器或其他类(我真的不确定),以获得这种JSON响应的行为?

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?

推荐答案

第一个响应似乎是分页响应,由分页序列化程序确定。您可以创建自定义分页序列化器将使用自定义格式。您正在寻找类似于以下内容的东西:

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"}
    ]
}

可以通过您的设置如文档中所述

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

这篇关于在Django Rest框架中哪里更改JSON响应的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆