重命名响应字段Django Rest Framework序列化程序 [英] Rename response fields django rest framework serializer

查看:262
本文介绍了重命名响应字段Django Rest Framework序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用djangorestframework调用一个简单的get API。我的模型是

I'm calling a simple get API using djangorestframework. My Model is

class Category(models.Model):
    category_id = models.AutoField(primary_key=True)
    category_name = models.CharField("Category Name", max_length = 30)
    category_created_date = models.DateField(auto_now = True, auto_now_add=False)
    category_updated_date = models.DateField(auto_now = True, auto_now_add=False)

    def __str__(self):
        return self.category_name

serializer.py

serializer.py

class CategorySerializer(serializers.ModelSerializer) :
    class Meta:
        model = Category
        fields = ['category_id', 'category_name']

def category_list(request):
    if request.method == 'GET':
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)

当我在网址并返回以下响应。

It's working fine when i hit request on the URL and returning following response.

[
    {
        "category_id": 1,
        "category_name": "ABC"
    }
]

我想更改响应字段名称,因为它仅适用于我的数据库,并且不想在响应中显示。如果我在序列化器类中更改名称,则不会出现字段匹配错误。

i want to change the response field names as it's for my DB only and don't want to disclose in response. If i change the name in serializer class than it's giving no field match error.

我还想自定义其他参数,例如上述响应对象中的带有消息和状态的响应对象,如下所示。

Also i want to customise other params like above response in response object with message and status like below.

{
status : 200,
message : "Category List",
response : [
        {
            "id": 1,
            "name": "ABC"
        }
    ]
}

需要适当的指导和流程。专家帮助。

Need a proper guide and flow. Experts help.

推荐答案

首先全部使用 category _ 在字段名称中是多余的。因为您已经将此字段分配给 Category 模型,并且通过执行此操作,所以正在为此字段创建命名空间。

First of all using category_ in field names is redundant. Because you are already assigning this fields to Category model, and by doing this you are creating "namespace" for this fields.

class Category(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField("Category Name", max_length = 30)
    created_date = models.DateField(auto_now = True, auto_now_add=False)
    updated_date = models.DateField(auto_now = True, auto_now_add=False)

    def __str__(self):
        return self.name

第二在Django id 自动创建自动字段,为什么您需要对其进行显式设置?

Second In django id AutoField is created automatically why would you need set it explicitly?

然后回答您的问题 序列化程序字段中的参数。

And answering your question There is source parameter in serializer fields.

class CategorySerializer(serializers.ModelSerializer):
    renamed_id = serializers.IntegerField(source='category_id')
    renamed_name = serializers.CharField(source='category_name')

    class Meta:
        model = Category
        fields = ['renamed_id', 'renamed_name']

然后您可以手动更改响应

And than you can change your response manually

from rest_framework import status

def category_list(request):
    if request.method == 'GET':
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        response = {
            'status': status.HTTP_200_OK,
            'message' : "Category List",
            'response' : serializer.data
        }
        return Response(response)

这篇关于重命名响应字段Django Rest Framework序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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