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
相关推荐
kuuailetianzi21 分钟前
Python初识:定位、优势与发展历程
python
guoran_shini30 分钟前
LLM微调-训练垂类问答模型
python·lora·sft
basketball61637 分钟前
Python FastAPI 介绍以及常用方法
python·fastapi·vllm·ai infra
论文复现现场1 小时前
企业知识库 RAG 用什么模型便宜?GLM-5.3-Flash 长文本 API 实测
python·rag·企业知识库·大模型api·glm-5.3-flash
梦在远山后1 小时前
从手写 Loop 到可恢复 Runtime:用 LangGraph、PostgreSQL Checkpoint 与 AG-UI 跑通中断恢复
python·langchain·agent
Yolanda_20222 小时前
8.tensorboard的使用
python
用户0332126663672 小时前
使用 Python 添加、隐藏或删除 PowerPoint 幻灯片
python
vx-程序开发2 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django
言乐62 小时前
Python关键词抓取目标网站
python·django·virtualenv·pygame·tornado
用户7783366132112 小时前
搜索页的 URL 状态管理:可分享、可回退、可刷新
python·api