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
相关推荐
Data_Journal6 分钟前
如何使用 Python 抓取 Google Flights:分步指南
大数据·开发语言·数据库·python·scrapy
你我一见如故23 分钟前
仿QQ音乐桌面客户端——测试报告
python·selenium
Kismet_nvi33 分钟前
Python 基础核心知识点总结
开发语言·windows·python
2401_8445829537 分钟前
冷门技巧:AI模型可靠性测试的实用技巧:数
python
you鬰43 分钟前
datawhale--llm-algo-leetcode5️⃣
python·datawhale
λqaq71 小时前
MySQL 数据库基础(2)约束、用户权限、远程连接、外键与 TCP/UDP 理解
linux·数据库·python·tcp/ip·mysql
人工干智能1 小时前
科普:pandas 时间偏移别名:ts.resample(“5Min“).sum()
python·pandas
开源量化GO1 小时前
最新AI辅助量化表达:先理清规则,再按需求选工具
人工智能·python
Zane19941 小时前
为什么 del 一个对象有时立刻消失,有时却纹丝不动?一文讲透引用计数与垃圾回收
后端·python
yichudu2 小时前
Python 装饰器 decorator
开发语言·python