python - 我如何在 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",
}
}
我应该对这种类型的输出做些什么改变!
解决方案
这个问题有一个简单的解决方案,你只需要在你的序列化器类中添加几行。
我假设您的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
它会解决你的问题:)
推荐阅读
- php - 需要借助 Windows 身份验证在 PHP 中集成 SSO
- wordpress - Wordpress:是否有一个 SHORTCODE 可以在前端输出注册表单?
- apache-spark - Pyspark - 对数据框进行非矢量化
- java - redis缓存中的自定义名称
- angular - cdk虚拟滚动的itemsize
- php - Magento 2 - 自定义支付模块前端错误
- css - CSS不适用于Wordpress中的密码保护页面
- python - 为什么当 mypy 需要类型注释时,愚蠢的注释会处理错误?
- mysql - 将 MSSQL 查询转换为 MySQL 5.7.23
- perl - 如何解析 {"access_token":"Abcd45689012031"}