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
相关推荐
落羽的落羽19 分钟前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Chasing__Dreams24 分钟前
大模型应用开发--13--RAG 查询优化策略
python
“AI国潮设计-小江”41 分钟前
《Python实战 | SDXL大模型批量生成“英歌舞海浪”蛋糕IP,附核心Prompt控制代码与IP授权变现思路》
人工智能·python·prompt·aigc
znnnk1 小时前
【Python】GUI 开发从入门到实战(三):PyQt/PySide 进阶之路
开发语言·python·pyqt
触底反弹3 小时前
面试被问到 Text2SQL,我用 DeepSeek 自己实现了一个
python·sqlite
2601_962295583 小时前
python+selenium实现自动化测试
自动化测试·python·selenium·学习心得·web端测试
青 春 记 忆3 小时前
零基础入门python66:FastAPI AI标题、摘要和标签
python·fastapi·后端开发
qq_22589174663 小时前
基于Python+Django的LangGraph智能旅游规划系统
python·django·旅游
青 春 记 忆4 小时前
零基础入门python65:FastAPI 安全调用大模型API
python·fastapi·后端开发
维克兜率天5 小时前
【维克】特征归一化与标准化:为什么模型对数据的“尺度“很敏感?
人工智能·笔记·python·机器学习·量化