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
相关推荐
Web3&Basketball3 分钟前
LLM 峰谷定价怎么吃满:一个能对账的错峰调度器
python·性能优化·大模型·任务调度·成本优化·deepseek·推理优化
2601_962218615 分钟前
万象生鲜系统订单全生命周期状态同步技术实现业务可视
大数据·数据库·人工智能·python·算法
FOAF-lambda10 分钟前
uiautomation-new 控件方位的使用
开发语言·python
OKkankan14 分钟前
LangChain能力详解!:从工具调用到 LangSmith——让聊天模型具备实时交互能力!
开发语言·python·langchain
2601_962298272 小时前
Python自动化脚本的编写01
python·appium·自动化脚本·web自动化·应收账款管理
新时代牛马2 小时前
镜像为什么越来越大?从Dockerfile、layer 到content-addressable store 讲透
django
AIFQuant2 小时前
Python实时外汇行情接入实战:WebSocket与REST K线查询
开发语言·python·websocket
babe小鑫3 小时前
生物统计学专业校招:SAS、R、Python学习顺序实用指南
python·学习·r语言
vx_Biye_Design3 小时前
springboot游泳馆系统93765-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·spring·课程设计
固定资产管理系统软件3 小时前
该去哪里找专业靠谱的智慧智能设备固定资产管理系统?
人工智能·python