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 小时前
Django QuerySet 懒加载与缓存机制源码级拆解文档
django
自学不成才12 小时前
深度复盘:一次flutter应用基于内存取证的黑盒加密破解实录并完善算法推理助手
c++·python·算法·数据挖掘
徐先生 @_@|||12 小时前
Palantir Foundry 五层架构模型详解
开发语言·python·深度学习·算法·机器学习·架构
深蓝电商API13 小时前
Scrapy爬虫限速与并发控制最佳实践
爬虫·python·scrapy
Derrick__113 小时前
淘宝MD5爬虫
爬虫·python
薛定谔的猫198213 小时前
llama-index Embedding 落地到 RAG 系统
开发语言·人工智能·python·llama-index
nimadan1215 小时前
**手机小说扫榜工具2025推荐,精准追踪榜单动态与题材风向
python·智能手机
编程武士15 小时前
Python 各版本主要变化速览
开发语言·python
傻啦嘿哟15 小时前
Python中的@property:优雅控制类成员访问的魔法
前端·数据库·python
sky172016 小时前
VectorStoreRetriever 三种搜索类型
python·langchain