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
相关推荐
珺毅同学5 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
骑士雄师5 小时前
18.4 长期记忆可修改版
python
~小先生~5 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫6 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
Dust-Chasing7 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
Cloud_Shy6188 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
abcy0712139 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
颜酱9 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
天天进步20159 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python
测试员周周9 小时前
【AI测试智能体-面试】AI测试面试60题(附回答思路)
人工智能·python·功能测试·测试工具·单元测试·自动化·测试用例