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
相关推荐
2401_838472519 分钟前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
CoLiuRs30 分钟前
语义搜索系统原理与实现
redis·python·向量·es
zhihuaba33 分钟前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
u01092727134 分钟前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
Stream_Silver1 小时前
【Agent学习笔记3:使用Python开发简单MCP服务】
笔记·python
穿过锁扣的风1 小时前
零基础入门 Python 爬虫:从基础到实战,爬取虎扑 / 豆瓣 / 图片全掌握
开发语言·爬虫·python
Stream_Silver2 小时前
【Agent学习笔记2:深入理解Function Calling技术:从原理到实践】
笔记·python
love530love2 小时前
技术复盘:llama-cpp-python CUDA 编译实战 (Windows)
人工智能·windows·python·llama·aitechlab·cpp-python·cuda版本
逄逄不是胖胖3 小时前
《动手学深度学习》-60translate实现
人工智能·python·深度学习
橘颂TA3 小时前
【测试】自动化测试函数介绍——web 测试
python·功能测试·selenium·测试工具·dubbo