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
相关推荐
卡提西亚4 分钟前
leetcode-179. 最大数
python·算法
AC赳赳老秦21 分钟前
时间开销自动统计:OpenClaw 记录工作任务时长、分析时间分配、给出优化建议
java·大数据·开发语言·python·自动化·deepseek·openclaw
清水白石00833 分钟前
Python 类定义阶段自动注册子类:从 `__init_subclass__` 到插件系统实战
linux·前端·python
用户83562907805138 分钟前
如何使用 Python 为 PDF 添加和管理图层
后端·python
祉猷并茂,雯华若锦41 分钟前
Appium 3.x 实战:元素定位与常见错误解析
开发语言·python·appium
jiang_changsheng1 小时前
Conda 的默认环境创建优先级。
linux·windows·python
FriendshipT1 小时前
Ultralytics:解读C2fCIB模块
人工智能·pytorch·python·深度学习·目标检测
c_lb72881 小时前
2026年AI量化学习流程,从表达开发走到分层验证
人工智能·python
s180579163622 小时前
低成本GEO优化技巧
人工智能·python
buhuizhiyuci2 小时前
【python篇——一周速通python语法】python的基础语法操作
开发语言·python