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
相关推荐
萧鼎4 分钟前
深入解析 Python 的 Word 模板引擎:docxtpl 全面指南
开发语言·python·word
Yeats_Liao11 分钟前
昇腾910B与DeepSeek:国产算力与开源模型的架构适配分析
人工智能·python·深度学习·神经网络·机器学习·架构·开源
智航GIS13 分钟前
11.3 Pandas 模块功能概览
python·信息可视化·pandas
浩子智控13 分钟前
开源RPA选择
python·c#·软件工程
kszlgy15 分钟前
Day48 随机函数与广播机制
python
子午19 分钟前
【2026原创】昆虫识别系统~Python+深度学习+卷积算法+模型训练+人工智能
人工智能·python·深度学习
nju_spy27 分钟前
动手学强化学习上交张伟楠(一)导论 + 多臂老虎机 MAB(ε-greedy+上置信界+汤普森采样)
人工智能·python·强化学习·actor-critic·多臂老虎机·汤普森采样·探索与利用
tjjucheng28 分钟前
专业做小程序定制开发的企业
python
ACERT33331 分钟前
6.吴恩达机器学习——TensorFlow与激活函数
人工智能·python·机器学习