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
相关推荐
梦想画家13 小时前
SQLMesh Python 模型入门(三):前后置语句、蓝图建模与避坑指南
大数据·python·sqlmesh
迅猛龙办公室13 小时前
Python实现绘制同切圆
开发语言·python
言乐614 小时前
Python语音检索
开发语言·python·django·virtualenv·pygame
泡茶喝茶写代码14 小时前
A股量化数据工程:从 REST 接口到策略信号(第 1 篇):指数列表与实时行情接入
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据接口
happylifetree15 小时前
Python34-35:核心语法-流程控制语句-循环-综合案例
python
吃饱了得干活15 小时前
Agent 的记忆与工具:从上下文窗口到 MCP
python·agent·mcp
燐妤15 小时前
LangGraph-复习总览
python·ai·面试·agent·学习方法·langgraph
尹人入圣16 小时前
市面上IP驱动产业新场景新工具
运维·网络·python·tcp/ip
打工仔折腾 AI16 小时前
从BPE到SentencePiece:Transformer分词原理与Python实战对比
android·人工智能·python·深度学习·langchain·transformer·ai agent 实战
骑着蜗牛撵大象32716 小时前
Qt 事件机制详解:从 QEvent 派生类到事件过滤器的全景指南
前端·python