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
相关推荐
CHANG_THE_WORLD7 分钟前
python 批量终止进程exe
开发语言·python
liann11913 分钟前
3.2_红队攻击框架--MITRE ATT&CK‌
python·网络协议·安全·网络安全·系统安全·信息与通信
云天AI实战派24 分钟前
AI 智能体问题排查指南:ChatGPT、API 调用到 Agent 上线失灵的全流程修复手册
大数据·人工智能·python·chatgpt·aigc
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
多思考少编码2 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛
ZhengEnCi2 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
ZhengEnCi2 小时前
M4-更新日志v0.1.3-Mermaid图表支持 📝
python
hsjcjh3 小时前
多模态长文本协同:用Gemini 3.1 Pro镜像官网破解复杂办公场景的效率困局(国内实测方案)
python
凯瑟琳.奥古斯特3 小时前
SQLAlchemy核心功能解析
开发语言·python·flask
卷Java3 小时前
GPTQ vs AWQ vs GGUF:模型量化工具横向测评
开发语言·windows·python