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 分钟前
企业PDF批量盖章开发集成指南:API对接OA/LIMS系统,高并发落地实战
开发语言·python·pdf
石山代码12 分钟前
类型限定符的底层实现原理是什么?
python
雾沉川17 分钟前
PyCharm 2025.2 完整安装与配置技术教程
ide·python·pycharm
眠りたいです23 分钟前
LangChainv1:agent快速上手与中间件认识
人工智能·python·中间件·langchain·langgraph
2601_9563198824 分钟前
期货报单被拒怎么识别与处理:order 状态与 last_msg 用法
python·区块链
yijianace30 分钟前
Python爬虫实战:分页爬取 + 详情页采集 + CSV存储
前端·爬虫·python
蜂蜜黄油呀土豆34 分钟前
Agent 循环:观察、思考、行动(ReAct 入门)
python·ai·大模型·react·js
SilentSamsara37 分钟前
特征工程系统方法论:编码、分箱、交互特征与特征选择
开发语言·人工智能·python·机器学习·青少年编程·信息可视化·pandas
财经资讯数据_灵砚智能38 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年6月8日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
geovindu44 分钟前
python:Coroutines Pattern
开发语言·python·设计模式·协程模式