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
相关推荐
谙忆8 分钟前
PNG改成ICO为什么不能用:用Python检查多尺寸目录与256px帧
开发语言·python
长空任鸟飞_阿康11 分钟前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·ai·架构·skills
滴啦嘟啦哒13 分钟前
【具身笔记】【原理探究】一、对PI05源码的实践笔记
笔记·python·vla·具身
miofly21 分钟前
GitHub 今日推荐|elephant-goldfish-model:先审查设计草案再写代码
python·开源·github
云和数据.ChenGuang30 分钟前
深入剖析 Python 的 MRO 规则:从 C3 线性化到实战踩坑
开发语言·python·1024程序员节
123_不打狼39 分钟前
Squidiff:基于条件扩散模型预测细胞发育与扰动响应
开发语言·python·squidiff
databook43 分钟前
用Python DSL 写轻量数据质检工具
python·数据分析
郝学胜-神的一滴1 小时前
AI 编程智能体 17:四步搞定专属AI智能体
大数据·人工智能·python·神经网络·算法·langchain·强化学习
岁寒良木1 小时前
麒麟 V10 (x86_64) 离线/联网部署 Docker 26.1.4 与 MaxKB v2.10 LTS 实战指南
python·docker·kylin
Norna1 小时前
receive 取消了,TCP 为什么还在读:AnyIO 的一次背压修复
python