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
相关推荐
小猴子爱上树25 分钟前
Temu批量视频翻译Python实现方案
开发语言·python·音视频
X1A0RAN39 分钟前
Python 并发请求性能优化实战
python·性能优化·并发编程
陈同学xxx1 小时前
Hermes Agent 接入飞书,在手机上随时聊天
linux·python·飞书
卷无止境1 小时前
Python 中基于 Qt 的 GUI 库授权方式全解析
后端·python
卷无止境1 小时前
Guardrails.ai:为大语言模型加一道"安全阀"
后端·python
汤姆小白5 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
向日的葵00612 小时前
langchain的Tools教程(三)
python·langchain·tools
言乐613 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
YUS云生13 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
智写-AI14 小时前
真实有效的免费降英文AI工具服务商
人工智能·python