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
相关推荐
江华森35 分钟前
exp01_Python_数据类型
开发语言·python
大鱼>1 小时前
模型可解释性:特征重要性/SHAP/LIME
人工智能·python·机器学习·lstm
代码不接地1 小时前
【时间序列预测】0.时间序列任务知识地图
python·ai编程
许彰午2 小时前
77_Python数据清洗实战技巧
开发语言·python
Sam09272 小时前
【AI 算法精讲 16】BPE 分词:从字节对到子词
人工智能·python·算法·ai
江华森2 小时前
04-python-面向对象
开发语言·python
梦帮科技2 小时前
基于EVM架构的Web3音频确权与RNS Token智能合约设计深度解析
人工智能·python·架构·web3·区块链·音视频·智能合约
AI行业学习2 小时前
Notepad++ 官方纯净下载+完整安装教程(Windows)【2026.7.5】
开发语言·windows·python·前端框架·html·notepad++
伏 念2 小时前
Hermes Agent
python