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
相关推荐
伊织code6 分钟前
PyTorch API 6 - 编译、fft、fx、函数转换、调试、符号追踪
pytorch·python·ai·api·-·6
struggle20259 分钟前
continue通过我们的开源 IDE 扩展和模型、规则、提示、文档和其他构建块中心,创建、共享和使用自定义 AI 代码助手
javascript·ide·python·typescript·开源
来自星星的坤21 分钟前
深入理解 NumPy:Python 科学计算的基石
开发语言·python·numpy
小声读源码41 分钟前
【技巧】使用UV创建python项目的开发环境
开发语言·python·uv·dify
程序员杰哥1 小时前
自动化测试基础知识详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
zm-v-159304339861 小时前
解锁遥感数据密码:DeepSeek、Python 与 OpenCV 的协同之力
开发语言·python·opencv
勘察加熊人1 小时前
Python+Streamlit实现登录页
开发语言·python
DavieLau1 小时前
Python开发后端InfluxDB数据库测试接口
服务器·数据库·python·时序数据库
文人sec2 小时前
接口自动化测试设计思路--设计实战
python·https·单元测试·自动化·pytest
子燕若水2 小时前
Flask 调试的时候进入main函数两次
后端·python·flask