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
相关推荐
钱栈up14 分钟前
奥迪上汽拍板「三年三款」,合资阵营的换挡节奏终于跟上了
爬虫·python·数据分析
东莞市云毅网络有限公司22 分钟前
SQLite FTS5 做中文问答检索:分词、排序与召回测试
python·sqlite·自动化运维·geo·数据监测
timeDifference₇11 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu11 小时前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命199113 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu13 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
fengkai454514 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.76114 小时前
:Python条件与循环语句学习总结
python
Wellijohn16 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*16 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理