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
相关推荐
Warson_L9 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅9 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅9 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L9 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅9 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L10 小时前
python的类&继承
python
Warson_L10 小时前
类型标注/type annotation
python
ThreeS12 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵14 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏