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
相关推荐
朝朝辞暮i1 分钟前
VLA 系统学习第 5 课:神经网络的参数到底是什么?——从 nn.Linear 真正理解 W、 b 和 Gradient
人工智能·python·深度学习·神经网络·vla
XZ-0700013 分钟前
week7-文本
python
Java后端的Ai之路14 分钟前
01-React基础教程
开发语言·前端·python·react.js·前端框架
我的xiaodoujiao24 分钟前
Django 基础知识详细图文教程 14-Django 表单定义与使用
开发语言·后端·python·django
2601_9628857234 分钟前
如何把 A 股行情高效存成 Parquet/Feather?
python
yi01139 分钟前
Leetcode 49 用 “身份证‘‘巧解
人工智能·笔记·python·算法·leetcode·哈希表
老歌老听老掉牙42 分钟前
基于STL模型的轴向截面轮廓提取与三维可视化方法
python·stl
yi0111 小时前
DAY22: LeetCode 733:图像渲染——从二维网格开始理解 DFS 和 BFS
数据结构·笔记·python·算法·leetcode·深度优先·宽度优先
Είναι η κοπέλα1 小时前
llama.cpp 与 GGUF 格式:本地大模型的“裸引擎“
开发语言·人工智能·pytorch·python·conda
大草原的小灰灰2 小时前
Python面向对象编程
开发语言·python