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
相关推荐
TomEval13 小时前
【测AI】第02篇:Python 环境搭建与基础语法速通
人工智能·python·功能测试·aigc
归去来 兮13 小时前
LangChain从入门到精通
python·langchain·langgraph
新时代牛马14 小时前
容器里拿到root 就等于宿主机沦陷?Capability、seccomp、AppArmor与user ns 讲透
django
淘气的小猴子14 小时前
Python 魔术方法入门
python
我要见SA姐114 小时前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
ide·vscode·python·自动化·编辑器
沉下心来学鲁班15 小时前
初识DeepAgents搭建第一个智能体
人工智能·python·langchain
ctlover15 小时前
数据结构:树
数据结构·python
触底反弹16 小时前
🐍 Python 语法全景图:一个 print() 引发的深度探索
python
烂蜻蜓16 小时前
Django入门教程(十六):Cookie与Session详解——用户状态管理的底层原理与实战
django
元Y亨H16 小时前
告别依赖地狱与打包崩溃:Python 项目环境治理与 PyInstaller 避坑实践
python