django drf to_representation

使用场景

1.需要对结果的中的某个字段进行进一步的处理;

2.模型类中没有的字段,添加到结果中进行响应;

例子

python 复制代码
from django.db import models


class TestModel(models.Model):
   name = models.CharField(_("名称"), max_length=50, null=True, blank=True, default="")
   status = models.CharField(_("状态"), max_length=10, null=True)
   create_by = models.ForeignKey(to='users.User', on_delete=models.SET_NULL, null=True)
   liked_by = models.ManyToManyField(to='users.User')


from rest_framework import serializers


class TestSerializer(serializers.ModelSerializer):
   class Meta:
       model = TestModel
       fields = '__all__'

   def to_representation(self, instance):
       # 调用父类获取当前序列化数据,instance代表每个对象实例obj
       data = super().to_representation(instance)
       # 对原字段的值作修改
       data['create_by'] = instance.create_by.name  # 显示用户表的名称,而不是用户ID
       # 添加新的字段--model没有的字段
       data['total_likes'] = instance.liked_by.count()  # 统计数量
       return data
相关推荐
星空椰7 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
凯瑟琳.奥古斯特7 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
风之所往_8 小时前
Python 3.4 新特性全面总结
python
太阳上的雨天8 小时前
任何格式的文件转Markdown
python·ai
yaoxin5211239 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
weixin_468466859 小时前
纳米 AI 搜索新手极速上手指南
人工智能·python·深度学习·搜索引擎·ai·语言模型·自然语言处理
凯瑟琳.奥古斯特9 小时前
数据库原理选择题精选
数据库·python·职场和发展
彦为君10 小时前
JavaSE-07-异常机制
java·开发语言·后端·python·spring
适应规律10 小时前
【无标题】
人工智能·python·算法