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
相关推荐
C^h5 小时前
python函数学习
人工智能·python·机器学习
Fanta丶5 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬5 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent
兜客互动6 小时前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_538601976 小时前
智能体测开Day30pytest测试框架
python
MC皮蛋侠客6 小时前
uv 系列(七):CI/CD、Docker 与私有索引——生产级交付
python·ci/cd·docker·uv
邪神与厨二病6 小时前
牛客周赛 Round 153
python·算法
yaoxin5211236 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
groundhappy6 小时前
idalib安装和codex ida-mcp配置
linux·开发语言·python
培之7 小时前
RTX 5090 安装 pytorch3d
人工智能·pytorch·python