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
相关推荐
岁月宁静8 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者8 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy199010 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk55511 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~17 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享18 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者18 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.19 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人20 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__20 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python