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
相关推荐
飞猪~2 小时前
LangChain python 版本 第一集
开发语言·python·langchain
2601_956319883 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
开飞机的舒克_4 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
霸道流氓气质4 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
人工智能时代 准备好了吗5 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
Metaphor6925 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
言乐66 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
fenglllle6 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding
cui_ruicheng6 小时前
Python从入门到实战(六):非序列容器
开发语言·python
百里香酚兰6 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习