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
相关推荐
2401_8714928534 分钟前
Layui如何修改Layui默认的UI主题颜色(换肤功能实现)
jvm·数据库·python
南子北游1 小时前
Python学习(基础语法1)
开发语言·python·学习
步辞1 小时前
Redis如何利用LFU算法优化缓存命中率
jvm·数据库·python
forEverPlume1 小时前
golang如何实现日志按级别过滤_golang日志按级别过滤实现教程
jvm·数据库·python
m0_624578593 小时前
MySQL主从复制支持跨版本吗_不同版本间同步的注意事项
jvm·数据库·python
yuanpan3 小时前
Python Pygame 入门教程:从零学会创建窗口、绘图和游戏交互
python·游戏·pygame
2401_871492853 小时前
如何在 React Router v6 中正确配置多路由组件显示
jvm·数据库·python
神仙别闹4 小时前
基于Python(Django)+MySQL 实现(Web)SQL智能检测系统的设计与实现
python·mysql·django
甄心爱学习4 小时前
【项目实训】法律文书智能摘要系统4
python·github·个人开发
huzhongqiang5 小时前
Playwright理解与封装
python