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
相关推荐
cui_ruicheng3 小时前
Python从入门到实战(十六):多进程编程
开发语言·python
_Jimmy_5 小时前
FastAPI + SQLAlchemy全局事务管理
python·fastapi
用户8356290780515 小时前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
AC赳赳老秦6 小时前
企业工商公开信息采集分析:OpenClaw 批量查询企业工商信息,生成企业画像报告
大数据·开发语言·python·自动化·php·deepseek·openclaw
FoldWinCard7 小时前
D6 Python 基础语法 --- 保留关键字
开发语言·python
暮暮祈安7 小时前
Celery 新手入门指南
java·数据库·python·flask·httpx
JustNow_Man8 小时前
每日高频场景英文口语
python
风吹心凉8 小时前
python3基础2026.7.22
开发语言·python
小猴子爱上树10 小时前
一站式解决图片视频翻译难题的高效AI工具
人工智能·python·音视频
weixin_5386019710 小时前
智能体测开Day31
开发语言·python