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
相关推荐
李帅51513 分钟前
用 CPU 做发票识别:从 OCR 文本行到结构化明细表的 4 个硬骨头
python
happylifetree1 小时前
Python79:核心语法-面向对象基础-实例方法
python
贝壳6902 小时前
bool-hybrid-array 9.13.6 偷偷加了个"按键自动升序"的字典,我翻出来测了下
python
艺杯羹2 小时前
MCP本地服务集成避坑:从Stdio管道僵死到双向JSON-RPC稳健通信
人工智能·python·ai·系统架构·大语言模型·ai编程·mcp
happylifetree2 小时前
Python78:核心语法-面向对象基础-类与对象
python
duansamve2 小时前
Python中进程
python
日日大王学编程3 小时前
AI Agent 技术发展历程、演进逻辑与技术范式综述
人工智能·python
春涧草茶3 小时前
慢就是快16-1协程
开发语言·前端·python
5233AI开发笔记3 小时前
API 返回 429:先区分限速、并发和配额,再决定是否重试
python
databook3 小时前
经常听到的透视表是干什么的?
python·数据分析·pandas