DRF 序列化组件练习
1479 字
7 分钟
DRF 序列化组件练习
【数据准备】模型层
from django.db import models
# Create your models here.class Book(models.Model): name = models.CharField(max_length=32) price = models.CharField(max_length=32) publish = models.ForeignKey(to="Publish", on_delete=models.SET_NULL, null=True, blank=True) authors = models.ManyToManyField(to="Author")
class Publish(models.Model): name = models.CharField(max_length=32) addr = models.CharField(max_length=32)
class Author(models.Model): name = models.CharField(max_length=32) phone = models.CharField(max_length=11) author_detail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)
class AuthorDetail(models.Model): email = models.CharField(max_length=32) age = models.IntegerField()【一】查询用户数据
【1】查询全部用户数据
- 路由层
# 查询全部path('author/all/', AuthorView.as_view()),- 视图
class AuthorView(APIView): back_dict = {"code": 100, "msg": "", "result": []}
def get(self, request): auth_obj = models.Author.objects.all() auth_ser = AuthorSerializer(instance=auth_obj, many=True) self.back_dict["msg"] = "获取成功!" self.back_dict["result"].append(auth_ser.data) return Response(self.back_dict)【2】查询指定用户数据
- 路由层
# 查询单条path('author/<int:pk>/', AuthorDetailsView.as_view()),- 视图
class AuthorDetailsView(APIView): back_dict = {"code": 100, "msg": "", "result": []}
def get(self, request, pk): author_obj = models.Author.objects.filter(pk=pk).first() auth_ser = AuthorSerializer(instance=author_obj) self.back_dict["msg"] = "获取成功!" self.back_dict["result"].append(auth_ser.data) return Response(self.back_dict)【二】新增用户数据
- 路由
# 查询全部path('author/all/', AuthorView.as_view()),# 查询单条path('author/<int:pk>/', AuthorDetailsView.as_view()),# 新增path('author/add/', AuthorView.as_view()),- 后端
class AuthorView(APIView): back_dict = {"code": 100, "msg": "", "result": []}
def get(self, request): auth_obj = models.Author.objects.all() auth_ser = AuthorSerializer(instance=auth_obj, many=True) self.back_dict["msg"] = "获取成功!" self.back_dict["result"].append(auth_ser.data) return Response(self.back_dict)
def post(self, request): # print(request.data) # {'name': '小东西', 'phone': 18298987878, 'email': '203@qq.com', 'age': 28}
auth_ser = AuthorSerializer(data=request.data) if auth_ser.is_valid(): auth_ser.save() self.back_dict["msg"] = "保存成功!" self.back_dict["result"].append(auth_ser.data) else: self.back_dict["msg"] = "保存失败!" self.back_dict["result"].append(auth_ser.errors) return Response(self.back_dict)【1】存储方式一
- 将传过来的数据通过source进行序列化
class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["id", "name", "phone", "email", "age"]
email = serializers.CharField(source="author_detail.email") age = serializers.IntegerField(source="author_detail.age")
# 保存数据 def create(self, validated_data): print(validated_data) # 'author_detail': {'email': '203@qq.com', 'age': 28} : 是因为上面的字段使用了 source 指定 , 自动帮我们进行了数据的格式化 # {'name': '小东西', 'phone': '18298987878', 'author_detail': {'email': '203@qq.com', 'age': 28}} # 先查看 validated_data 的数据格式,再决定怎么存 # (1) 将 作者详细信息 弹出 auth_detail = validated_data.pop("author_detail") # (2)存储详细信息 auth_detail_obj = AuthorDetail.objects.create(**auth_detail) print(auth_detail_obj.pk) # (3)将剩下的信息打散传入 # 将生成创建的相信信息 添加到 信息字典里 ---- 因为后面打散数据,然后需要绑定外键字段 # validated_data["author_detail_id"] = auth_detail_obj.pk validated_data["author_detail"] = auth_detail_obj print(validated_data) auth_obj = Author.objects.create(**validated_data) return auth_obj【2】存储方式二
- 不通过 source 序列化
- 而是直接将数据打散
class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["id", "name", "phone", "email", "age", 'detail_email', 'detail_age']
# 只用来读取数据 -- 只读 detail_email = serializers.CharField(source="author_detail.email", read_only=True) detail_age = serializers.IntegerField(source="author_detail.age", read_only=True)
# 只用来存储数据 -- 只写 email = serializers.CharField(write_only=True) age = serializers.IntegerField(write_only=True)
# 保存数据 def create(self, validated_data): # print(validated_data) # 'author_detail': {'email': '203@qq.com', 'age': 28} : 是因为上面的字段使用了 source 指定 , 自动帮我们进行了数据的格式化 # {'name': '小东西', 'phone': '18298987878', 'author_detail': {'email': '203@qq.com', 'age': 28}} # {'name': '小东西', 'phone': '18298987878', 'email': '203@qq.com', 'age': 28} # 先查看 validated_data 的数据格式,再决定怎么存 author_detail_obj = AuthorDetail.objects.create(email=validated_data.get('email'), age=validated_data.get('age')) auth_obj = Author.objects.create(name=validated_data.get('name'), phone=validated_data.get("phone"), author_detail=author_detail_obj) return auth_obj【三】修改用户数据
- 路由层
# 修改path('author/put/<int:pk>/', AuthorDetailsView.as_view()),- 视图层
class AuthorDetailsView(APIView): back_dict = {"code": 100, "msg": "", "result": []}
def put(self, request, pk): # 根据用户id查到指定的用户 author_obj = models.Author.objects.filter(pk=pk).first() auth_ser = AuthorSerializer(instance=author_obj, data=request.data) if auth_ser.is_valid(): auth_ser.save() self.back_dict["msg"] = "修改成功!" # self.back_dict["result"].append(auth_ser.data) else: self.back_dict["msg"] = "修改失败!" self.back_dict["result"].append(auth_ser.errors) return Response(self.back_dict)- 序列化类
class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["id", "name", "phone", "email", "age", 'detail_email', 'detail_age']
# 只用来读取数据 -- 只读 detail_email = serializers.CharField(source="author_detail.email", read_only=True) detail_age = serializers.IntegerField(source="author_detail.age", read_only=True)
# 只用来存储数据 -- 只写 email = serializers.CharField(write_only=True) age = serializers.IntegerField(write_only=True)
# 保存数据 def create(self, validated_data): # print(validated_data) # 'author_detail': {'email': '203@qq.com', 'age': 28} : 是因为上面的字段使用了 source 指定 , 自动帮我们进行了数据的格式化 # {'name': '小东西', 'phone': '18298987878', 'author_detail': {'email': '203@qq.com', 'age': 28}} # {'name': '小东西', 'phone': '18298987878', 'email': '203@qq.com', 'age': 28} # 先查看 validated_data 的数据格式,再决定怎么存 author_detail_obj = AuthorDetail.objects.create(email=validated_data.get('email'), age=validated_data.get('age')) auth_obj = Author.objects.create(name=validated_data.get('name'), phone=validated_data.get("phone"), author_detail=author_detail_obj) return auth_obj
# 重写update 方法 def update(self, instance, validated_data): # instance 就是 author 对象 ----> 能拿到 author_detail 对象 # validated_data : {'name': '小东西', 'phone': '18298987878', 'email': '203@qq.com', 'age': 28} instance.name = validated_data.get('name') instance.phone = validated_data.get('phone') instance.author_detail.email = validated_data.get('email') instance.author_detail.age = validated_data.get('age')
instance.save() instance.author_detail.save() return instance【四】删除用户数据
- 路由层
# 删除path('author/del/<int:pk>/', AuthorDetailsView.as_view()),- 视图
class AuthorDetailsView(APIView): back_dict = {"code": 100, "msg": "", "result": []} def delete(self, request, pk): # 根据用户id查到指定的用户 author_obj = models.Author.objects.filter(pk=pk).first() # 在用户详情表中将用户所对应的信息删除 --- 级联删除 models.AuthorDetail.objects.filter(pk=author_obj.author_detail.pk).delete() self.back_dict["msg"] = "删除成功!" return Response(self.back_dict)【总结】
【models.py】
from django.db import models
# Create your models here.class Author(models.Model): name = models.CharField(max_length=32) phone = models.CharField(max_length=11) author_detail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)
class AuthorDetail(models.Model): email = models.CharField(max_length=32) age = models.IntegerField()【urls.py】
from .views import *
urlpatterns = [ # 查询全部 path('author/all/', AuthorView.as_view()), # 查询单条 path('author/<int:pk>/', AuthorDetailsView.as_view()), # 新增 path('author/add/', AuthorView.as_view()), # 删除 path('author/del/<int:pk>/', AuthorDetailsView.as_view()), # 修改 path('author/put/<int:pk>/', AuthorDetailsView.as_view()),]【views.py】
from app01.serializers.MY_serializer import BookSerializer, AuthorSerializer, AuthorDetailSerializerfrom rest_framework.views import APIViewfrom app01 import modelsfrom rest_framework.response import Response
class AuthorView(APIView): back_dict = {"code": 100, "msg": "", "result": []}
def get(self, request): auth_obj = models.Author.objects.all() auth_ser = AuthorSerializer(instance=auth_obj, many=True) self.back_dict["msg"] = "获取成功!" self.back_dict["result"].append(auth_ser.data) return Response(self.back_dict)
def post(self, request): # print(request.data) # {'name': '小东西', 'phone': 18298987878, 'email': '203@qq.com', 'age': 28}
auth_ser = AuthorSerializer(data=request.data) if auth_ser.is_valid(): auth_ser.save() self.back_dict["msg"] = "保存成功!" # self.back_dict["result"].append(auth_ser.data) else: self.back_dict["msg"] = "保存失败!" self.back_dict["result"].append(auth_ser.errors) return Response(self.back_dict)
class AuthorDetailsView(APIView): back_dict = {"code": 100, "msg": "", "result": []}
def get(self, request, pk): author_obj = models.Author.objects.filter(pk=pk).first() auth_ser = AuthorSerializer(instance=author_obj) self.back_dict["msg"] = "获取成功!" self.back_dict["result"].append(auth_ser.data) return Response(self.back_dict)
def put(self, request, pk): # 根据用户id查到指定的用户 author_obj = models.Author.objects.filter(pk=pk).first() auth_ser = AuthorSerializer(instance=author_obj, data=request.data) if auth_ser.is_valid(): auth_ser.save() self.back_dict["msg"] = "修改成功!" # self.back_dict["result"].append(auth_ser.data) else: self.back_dict["msg"] = "修改失败!" self.back_dict["result"].append(auth_ser.errors) return Response(self.back_dict)
def delete(self, request, pk): # 根据用户id查到指定的用户 author_obj = models.Author.objects.filter(pk=pk).first() # 在用户详情表中将用户所对应的信息删除 --- 级联删除 models.AuthorDetail.objects.filter(pk=author_obj.author_detail.pk).delete() self.back_dict["msg"] = "删除成功!" return Response(self.back_dict)【serializer.py】
from rest_framework import serializersfrom app01.models import Book, Author, AuthorDetail
class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["id", "name", "phone", "email", "age", 'detail_email', 'detail_age']
# 只用来读取数据 -- 只读 detail_email = serializers.CharField(source="author_detail.email", read_only=True) detail_age = serializers.IntegerField(source="author_detail.age", read_only=True)
# 只用来存储数据 -- 只写 email = serializers.CharField(write_only=True) age = serializers.IntegerField(write_only=True)
# 保存数据 def create(self, validated_data): # print(validated_data) # 'author_detail': {'email': '203@qq.com', 'age': 28} : 是因为上面的字段使用了 source 指定 , 自动帮我们进行了数据的格式化 # {'name': '小东西', 'phone': '18298987878', 'author_detail': {'email': '203@qq.com', 'age': 28}} # {'name': '小东西', 'phone': '18298987878', 'email': '203@qq.com', 'age': 28} # 先查看 validated_data 的数据格式,再决定怎么存 author_detail_obj = AuthorDetail.objects.create(email=validated_data.get('email'), age=validated_data.get('age')) auth_obj = Author.objects.create(name=validated_data.get('name'), phone=validated_data.get("phone"), author_detail=author_detail_obj) return auth_obj
# 重写update 方法 def update(self, instance, validated_data): # instance 就是 author 对象 ----> 能拿到 author_detail 对象 # validated_data : {'name': '小东西', 'phone': '18298987878', 'email': '203@qq.com', 'age': 28} instance.name = validated_data.get('name') instance.phone = validated_data.get('phone') instance.author_detail.email = validated_data.get('email') instance.author_detail.age = validated_data.get('age')
instance.save() instance.author_detail.save() return instance支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!
相关文章智能推荐
1
Firefly 接入站点日历页面
Web 开发为 Firefly 增加独立站点日历,汇总节日、纪念日、安排和文章发布日期,并记录配置、交互与侧栏时间进度卡片的实现。
2
Firefly 博客接入 Waline 评论系统
Web 开发对比 Firefly 内置评论方案,记录使用 Vercel 与 Neon 部署 Waline、绑定域名、注册管理员及接入博客的完整流程。
3
NAS 与 Syncthing 多端笔记同步
运维与系统管理使用 Syncthing 在 NAS、Mac 与 Windows 之间同步 Typora 笔记和图片,记录 Docker Compose 部署、设备配对、NetsGo 外网转发,以及版本保留、权限和带宽排查。
4
Nexus Terminal 学习笔记:Web 远程连接与部署运维
运维与系统管理记录 Nexus Terminal 的 Docker Compose 部署、HTTPS 与 WebSocket 反向代理,以及 SSH、SFTP、RDP、VNC 连接管理,整理登录保护、会话挂起、备份升级和常见排障方法。
5
C 语言发展史
编程语言了解 C 语言从 BCPL、B 语言到现代标准 C 的发展历程、核心特点与应用领域。
随机文章随机推荐














