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
相关推荐
GDAL28 分钟前
uv 完整教程:下一代 Python 包管理工具
python·uv
曲幽8 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶8 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..8 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵9 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf9 小时前
Python 模块与包的导入导出
前端·后端·python
ice8130331819 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf9 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福10 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf11 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python