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
相关推荐
独行soc1 分钟前
2026年渗透测试面试题总结-5(题目+回答)
android·网络·python·安全·web安全·渗透测试
玩大数据的龙威5 分钟前
农经权二轮延包—一键出承包地块调查表
数据库·python
越甲八千5 分钟前
python socket
开发语言·python
爱吃肉的鹏14 分钟前
树莓派4B安装pytorch
人工智能·pytorch·python
_leoatliang19 分钟前
基于Python的深度学习以及常用环境测试案例
linux·开发语言·人工智能·python·深度学习·算法·ubuntu
leiming620 分钟前
C语言联合体union的用法(非常详细,附带示例)
java·python·算法
Dxy123931021632 分钟前
Python的PIL如何转Base64字符串:完整指南
开发语言·python
FJW02081432 分钟前
Python正则表达式
python·正则表达式
invicinble43 分钟前
对于后端要和linux打交道要掌握的点
linux·运维·python
喵手1 小时前
Python爬虫零基础入门【第三章:Requests 静态爬取入门·第4节】列表页→详情页:两段式采集(90%项目都这样)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·requests静态爬取·两段式采集