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
相关推荐
我的xiaodoujiao15 分钟前
快速学习Python基础知识详细图文教程18--多线程
开发语言·python·学习·测试工具
❀搜不到1 小时前
isat-sam分割导出掩码图
开发语言·python
Zane19941 小时前
ClassName() 只是一步?拆开看 __new__ 和 __init__ 各自在干什么
后端·python
曾阿伦2 小时前
Trae CN Python环境调试debug指南
开发语言·python
渣男教父2 小时前
Python游戏自动化实战案例
python·编程语言
天天爱吃肉82182 小时前
【工程师笔记|新能源整车电控一次过CISPR25/BCI,汽车EMC/EMI落地十大核心设计技巧】
大数据·人工智能·笔记·python·汽车
m0_617493942 小时前
Python 使用 cryptography 实现数据加密与解密
开发语言·python
万山寒3 小时前
python依赖包导出离线安装到没有外网的服务器
服务器·开发语言·python
程序员雷欧3 小时前
LongAdder
开发语言·python
月光船幽幽3 小时前
分层阈值规避归藏协议过度重置
人工智能·python