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
相关推荐
2601_9622838831 分钟前
Django数据库配置(一)
mysql·postgresql·django·sqlite·数据库配置
用户03321266636741 分钟前
快速合并 Word 文档【Python 指南】
python
威联通网络存储44 分钟前
TS-h987XU-RP 在化工制造批次数据场景的部署
python·制造
m0_547486661 小时前
《Python爬虫大数据采集与挖掘》全套PPT课件2026
爬虫·python·powerpoint
CV山月1 小时前
《DPO 算法详解:不训练奖励模型,如何让大模型直接学会人类偏好?》
人工智能·经验分享·python·大模型·强化学习·研究生
ctlover1 小时前
网络编程和多线程
开发语言·网络·python
Mr_liu_6661 小时前
ns3-gym例子解析_基础例子与wifi例子_DQN(3)
开发语言·c++·python·dqn·ns3
weixin_440730501 小时前
playwright实战-渠道应用操作
开发语言·前端·python
asdzx671 小时前
Python 解析 Excel 数据、图片与图表的实现方案
python·excel
砚底藏山河1 小时前
存储选型实战:CSV-SQLite-MySQL同机基准(魔码量化实战 #02)
java·数据库·python·金融·maven