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
相关推荐
小小测试开发6 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想7 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波7 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf8 小时前
Python 异常处理
前端·后端·python
麻雀飞吧8 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy8 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.9 小时前
【01】Python 机器学习
开发语言·python
为爱停留9 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t9 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦9 小时前
Python 搭建简易HTTP服务
开发语言·python·http