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
相关推荐
ValhallaCoder2 小时前
hot100-栈
数据结构·python·算法·
MediaTea5 小时前
Python:生成器表达式详解
开发语言·python
-To be number.wan6 小时前
Python数据分析:SciPy科学计算
python·学习·数据分析
Dxy12393102166 小时前
DataFrame数据修改:从基础操作到高效实践的完整指南
python·dataframe
overmind7 小时前
oeasy Python 115 列表弹栈用pop删除指定索引
开发语言·python
hnxaoli8 小时前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
电饭叔8 小时前
文本为 “ok”、前景色为白色、背景色为红色,且点击后触发 processOK 回调函数的 tkinter 按钮
开发语言·python
雷电法拉珑9 小时前
财务数据批量采集
linux·前端·python
shangjian00710 小时前
Python基础-With关键字
python
zchxzl11 小时前
亲测2026京津冀可靠广告展会
大数据·人工智能·python