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
相关推荐
暮冬-  Gentle°6 分钟前
用Python制作一个文字冒险游戏
jvm·数据库·python
小小小米粒19 分钟前
[特殊字符] 正常部署 AI + 流式输出(Stream)[特殊字符] 为什么会 CPU 炸了?
开发语言·python
站大爷IP22 分钟前
Python异步编程:asyncio核心用法与避坑指南
python
m0_5879589529 分钟前
游戏与图形界面(GUI)
jvm·数据库·python
不剪发的Tony老师33 分钟前
Spyder:一款面向数据科学的Python集成开发环境
ide·python
众创岛1 小时前
python中enumerate的用法
开发语言·python
布史1 小时前
Prometheus Python Client 实操指南:从零实现自定义 Exporter
网络·python·prometheus
纤纡.1 小时前
矿物识别分类:8 种机器学习算法对比与实战(平均值填充数据集)
python·深度学习·算法·机器学习
2301_818419011 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
代码探秘者2 小时前
【算法篇】3.位运算
java·数据结构·后端·python·算法·spring