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
相关推荐
西西弗Sisyphus13 分钟前
YOLO26 自定义损失函数 重写 init_criterion 方法 损失类不继承基类
pytorch·python·yolo·yolo11·yolo26
装不满的克莱因瓶30 分钟前
RLHF中的PPO算法——大语言模型对齐优化的核心引擎
人工智能·python·深度学习·算法·机器学习·语言模型·自然语言处理
c_lb728839 分钟前
期货主连研究具体月实盘:KQ 连续与标的月份偏差怎么记
python·区块链
绘梨衣54740 分钟前
采集基类设计遇到的描述符bug
爬虫·python·bug
TechWayfarer1 小时前
IP精准定位服务在保险行业的接入实践:区域需求洞察与精准服务
数据库·python·tcp/ip·flask
Li#1 小时前
AI编写操作使用说明书需要用到的工具和能力
python·ai编程·ai写作
红宝村村长1 小时前
torch.autograd.Function.apply()
开发语言·python
花间相见2 小时前
【LeetCode01】—— 无重复字符的最长子串:滑动窗口经典题详解
python·算法·leetcode
何以解忧,唯有..2 小时前
Python 中的继承机制:从基础到高级用法详解
java·开发语言·python
try2find2 小时前
agent环境安装spacy
python·智能体