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
相关推荐
万粉变现经纪人11 分钟前
如何解决 pip install 编译报错 ‘cl.exe’ not found(缺少 VS C++ 工具集)问题
开发语言·c++·人工智能·python·pycharm·bug·pip
r***113315 分钟前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
___波子 Pro Max.1 小时前
Python类型注解详解与应用
python
1***Q7841 小时前
Python增强现实案例
开发语言·python·ar
Q26433650231 小时前
【有源码】spark与hadoop-情感挖掘+画像建模的携程酒店评价数据分析可视化系统-基于机器学习的携程酒店评价情感分析与竞争态势可视化
大数据·hadoop·python·机器学习·数据分析·spark·毕业设计
倚肆2 小时前
Spring Boot 中的 Bean 与自动装配详解
spring boot·后端·python
不剪发的Tony老师2 小时前
PyScripter:一款免费开源、功能强大的Python开发工具
ide·python
FL171713147 小时前
Pytorch保存pt和pkl
人工智能·pytorch·python
爱学习的小道长9 小时前
进程、线程、协程三者的区别和联系
python·ubuntu
L-李俊漩10 小时前
MMN-MnnLlmChat 启动顺序解析
开发语言·python·mnn