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
相关推荐
AI科技星6 分钟前
时空运动的几何约束:张祥前统一场论中圆柱螺旋运动光速不变性的严格数学证明与物理诠释
服务器·数据结构·人工智能·python·科技·算法·生活
AIsdhuang12 分钟前
2025 AI培训权威榜:深度评测与趋势前瞻
人工智能·python·物联网
m0_7269659815 分钟前
RAG小实战
开发语言·python
只与明月听19 分钟前
FastAPI入门实战
前端·后端·python
无心水30 分钟前
【Python实战进阶】12、Python面向对象编程实战:从零构建搜索引擎,掌握封装、继承与多态!
开发语言·python·搜索引擎·python进阶·python面向对象·搜索引擎实战·封装继承多态
mortimer30 分钟前
Python + FFmpeg 视频自动化处理指南:从硬件加速到精确剪辑
python·ffmpeg·音视频开发
帅得不敢出门32 分钟前
Android8 Framework实现Ntp服务器多域名轮询同步时间
android·java·服务器·python·framework·github
haiyu_y1 小时前
Day 29 异常处理
python
古城小栈1 小时前
Python 3.14:重塑开发体验的五大技术突破与实践指南
开发语言·python
小糖学代码1 小时前
LLM系列:1.python入门:1.初识python
服务器·开发语言·人工智能·python·ai