【6.0作业】

发布时间 2023-07-31 12:24:29作者: Chimengmeng

【数据准备】模型层

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, AuthorDetailSerializer
from rest_framework.views import APIView
from app01 import models
from 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 serializers
from 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