首页 > 解决方案 > 我如何在 django rest 框架中获取字符串格式的主键

问题描述

我目前正在开发 django rest 框架项目,响应输出的要求如下所述。

如果有人对此有任何想法,那将对我非常有帮助。

目前我得到这样的输出:

{
    "status": true,
    "message": "User Details",
    "Detail": {
        "id": 1,
        "phone": "9874563120",
        "first_name": "Crish",
        "birthdate": "1989-09-16",
        "age": 32,
        "email": "crish@gmail.com",

    }
}

但我想得到这样的输出:

    {
    "status": true,
    "message": "User Details",
    "Detail": {
        "id": "1", #in string formate
        "phone": "9874563120",
        "first_name": "Crish",
        "birthdate": "1989-09-16",
        "age": "32", #in string formate
        "email": "crish@gmail.com",

    }
}

我应该对这种类型的输出做些什么改变!

标签: pythondjangodjango-rest-framework

解决方案


这个问题有一个简单的解决方案,你只需要在你的序列化器类中添加几行。

我假设您的serializers.py文件如下所示:

serializers.py

class UserSerializer(serializers.ModelSerializer): #Assumed class name 

class Meta:
    model = User #Assumed model name 
    fields = ['id','phone','first_name','birthdate','age','email']

#you just need to add following representation function after your `Meta class`

def to_representation(self, instance):
    repr = super().to_representation(instance)
    repr['id'] = str(repr['id'])
    repr['age'] = str(repr['age'])

    return repr

它会解决你的问题:)


推荐阅读