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
相关推荐
Eric.Lee202115 分钟前
mujoco读取模型几何体属性
python·物理引擎·mujoco·物理仿真·构建物理几何体
子午18 分钟前
【车辆车型识别系统】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积网络+resnet50算法
人工智能·python·深度学习
独行soc24 分钟前
2025年渗透测试面试题总结-273(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
独行soc25 分钟前
2025年渗透测试面试题总结-274(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
CHANG_THE_WORLD28 分钟前
Python列表(List)介绍
windows·python·list
Byron Loong34 分钟前
【Debug】vscode 调试python,如何配置固定调试文件
ide·vscode·python
大叔_爱编程44 分钟前
基于大数据的短视频用户兴趣分析-hive+django+spider
大数据·hive·django·毕业设计·源码·课程设计·spider
qq_3561969544 分钟前
day31函数专题2:装饰器@浙大疏锦行
python
爱学习的梵高先生1 小时前
Python:变量
python
齐齐大魔王1 小时前
python爬虫学习进程(四)
爬虫·python·学习