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
相关推荐
Yolanda_202221 分钟前
在vscode终端中可使用pip,但是cmd终端中找不到命令 pip问题的解决
vscode·python·conda·pip
2301_7644413333 分钟前
用动力学系统(微分方程)为 Kernberg 的客体关系单元提供数学化的操作定义,把“自体—客体“这对心理结构建模成一个二维耦合系统
数据结构·python·算法·数学建模
dogstarhuang1 小时前
用 Doubao-Seed-Evolving + Python 免费写一个网页正文提取工具(实战教程)
爬虫·python·ai编程
猫头虎1 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
心运软件2 小时前
Python实战:中国大学排行榜数据采集与可视化大屏
后端·python
长不胖的路人甲2 小时前
什么是赫夫曼树(哈夫曼树 / Huffman Tree)
python·算法·霍夫曼树
魔镜er2 小时前
03-张量
人工智能·pytorch·python
37.2℃9953 小时前
Claude Design哪个公司技术好
python·设计模式
157092511343 小时前
【无标题】
开发语言·python·算法
AI工具人PM产品经理3 小时前
CSDN 自动发布全流程实战:从 CKEditor HTML 注入到创作页就地发布
python