Django用rest_framework里的serializers.ModelSerializer序列化 - Go语言中文社区

Django用rest_framework里的serializers.ModelSerializer序列化


序列化组件的使用及接口设计

  1. 请求接口设计get请求所有数据(restapi规范)

      GET						127.0.0.1:8000/books/			# 获取所有数据, 返回值:[{}, {}, {}]
      GET						127.0.0.1:8000/books/{id}       # 获取一条数据, 返回值:{}
      POST					    127.0.0.1:8000/books/			# 新增一条数据, 返回值:{}
      PUT						127.0.0.1:8000/books/{id}       # 修改一条数据, 返回值:{}
      DELETE                    127.0.0.1:8000/books/{id}       # 删除一条数据, 返回值: 空对象
    
  2. 创建model.py

    1. python manage.py makemigrations
    2. python manage.py migrate
  3. urls.py

  4. views.py

    1. 开始使用序列化

      1. 导入模块 from rest_framework import serializers

      2. 建立一个序列化类

        class BookSerializer(serializers.ModelSerializer):
          	字段可以自定义
        
      3. 获取queryset

        ​ origin_data = BookInfo.objects.all()

      4. 开始序列化

        serialized_data = BookSerializer(origin_data, many=True )

      5. 序列化后的数据, 返回给客户端

        return Response(serialized_data.data)

GET所有数据案例

  1. 创建模型类

    from django.db import models
    
    from datetime import datetime
    # from django.contrib.auth.models import AbstractUser
    
    
    class AuthorInfo(models.Model):
        name = models.CharField(max_length=32, verbose_name="作者名称")
        age = models.IntegerField(verbose_name="作者年龄")
    
        class Meta:
            db_table = "db_author_info"
            verbose_name = "作者信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class PublishInfo(models.Model):
        name = models.CharField(max_length=32, verbose_name="出版社名称")
        city = models.CharField(max_length=32, verbose_name="出版社所在城市")
        email = models.EmailField(verbose_name="出版社邮箱")
    
        class Meta:
            db_table = "db_publish_info"
            verbose_name = "出版社信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class BookInfo(models.Model):
        title = models.CharField(max_length=32, verbose_name="书名")
        publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")
    
        # max_digits小数位加整数位多少长度 decimal_places小数位长度为2
        price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")
        
        # on_delete
        # CASCADE:这就是默认的选项,级联删除,你无需显性指定它。
    		# PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。
    		# SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。
    		# SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
    		# SET(): 自定义一个值,该值当然只能是对应的实体了
        publish = models.ForeignKey(PublishInfo, related_name="book", related_query_name="book_query", on_delete=models.CASCADE, verbose_name="出版社")
        # ManyToManyField多对多
        authors = models.ManyToManyField(AuthorInfo, verbose_name="图书作者")
    
        class Meta:
            db_table = "db_book_info"
            verbose_name = "图书信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.title
    
    
  2. 创建urls.py

    from django.urls import re_path
    from .views import BookView
    
    urlpatterns = [
      	# restapi风格定制路由
        re_path(r"^books/$", BookView.as_view()),
    ]
    
    
  3. 创建views.py

    1. 导入模块

      # 第一步: 导入模块
      from rest_framework import serializers
      
    2. 建立序列化类

      class BookSerializer(serializers.ModelSerializer):
          class Meta:
              # 指定    要操作的模型类
              model = BookInfo
      
              # 指定序列化的字段
              fields = (
                  "title",
                  "price",
                  "publishDate",
                  "publish",
                  "authors",
                  "author_list",
                  "publish_name",
                  "publish_city"
              )
      
              # 指定那些字段是只写的
              # write_only只写的 (只写的 前端发送数据时要写它, 后端返回数据时没有它)
              extra_kwargs = {
                  "publish": {"write_only": True},
                  "authors": {"write_only": True}
              }
      
          # 自定义的字段
          # read_only只读的 (只读的 前端发送数据时不用写它, 后端返回数据时有它)
          publish_name = serializers.CharField(max_length=32, read_only=True, source="publish.name")
          publish_city = serializers.CharField(max_length=32, read_only=True, source="publish.city")
      
          author_list = serializers.SerializerMethodField()
      
          def get_author_list(self, book_obj):
              # 拿到queryset开始循环 [ {}, {}, {}]
              authors = []
      				
              # book_obj.authors.all() 获取所有author对象
              for author in book_obj.authors.all():
                  authors.append(author.name)
              return authors
      
      
    3. 获取queryset/开始序列化/序列化后的数据, 返回给客户端

      from rest_framework.views import APIView
      # Response返回序列化对象
      from rest_framework.response import Response
      
      from .models import BookInfo, PublishInfo, AuthorInfo
      from .app_serializers import BookSerializer
      
      
      class BookView(APIView):
          def get(self, request):
              # 第三步: 获取queryset
              origin_data = BookInfo.objects.all()
      
              # 第四步: 开始序列化
              # 当序列化多条数据时 要加上many=True
              serialized_data = BookSerializer(origin_data, many=True)
      				
           # 返回序列化对象
              # 记住序列化的值在data属性里
              # 所以这里用serialized_data.data取序列化的值
              return Response(serialized_data.data)
      
    4. postman效果图
      在这里插入图片描述

序列化组件的使用及接口设计

  1. 请求接口设计post新增一条数据(restapi规范)

    GET						127.0.0.1:8000/books/			# 获取所有数据, 返回值:[{}, {}, {}]
    GET						127.0.0.1:8000/books/{id}       # 获取一条数据, 返回值:{}
    POST					127.0.0.1:8000/books/			# 新增一条数据, 返回值:{}
    PUT						127.0.0.1:8000/books/{id}       # 修改一条数据, 返回值:{}
    DELETE                  127.0.0.1:8000/books/{id}       # 删除一条数据, 返回值: 空对象
    
  2. 创建model.py

    1. python manage.py makemigrations
    2. python manage.py migrate
  3. urls.py

  4. views.py

    1. 开始使用序列化

      1. 导入模块 from rest_framework import serializers

      2. 建立一个序列化类

        class BookSerializer(serializers.ModelSerializer):
          	字段可以自定义
        
      3. 获取客户端请求数据
        client_data = request.data

      4. 开始序列化

        verified_data = BookSerializer(data=client_data, many=False)

      5. 写入数据库
        verified_data.save()

      6. 序列化后的数据, 返回给客户端

        return Response(serialized_data.data)

POST案例

  1. 创建模型类

    from django.db import models
    
    from datetime import datetime
    # from django.contrib.auth.models import AbstractUser
    
    
    class AuthorInfo(models.Model):
        name = models.CharField(max_length=32, verbose_name="作者名称")
        age = models.IntegerField(verbose_name="作者年龄")
    
        class Meta:
            db_table = "db_author_info"
            verbose_name = "作者信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class PublishInfo(models.Model):
        name = models.CharField(max_length=32, verbose_name="出版社名称")
        city = models.CharField(max_length=32, verbose_name="出版社所在城市")
        email = models.EmailField(verbose_name="出版社邮箱")
    
        class Meta:
            db_table = "db_publish_info"
            verbose_name = "出版社信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class BookInfo(models.Model):
        title = models.CharField(max_length=32, verbose_name="书名")
        publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")
    
        # max_digits小数位加整数位多少长度 decimal_places小数位长度为2
        price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")
        
        # on_delete
        # CASCADE:这就是默认的选项,级联删除,你无需显性指定它。
    		# PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。
    		# SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。
    		# SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
    		# SET(): 自定义一个值,该值当然只能是对应的实体了
        publish = models.ForeignKey(PublishInfo, related_name="book", related_query_name="book_query", on_delete=models.CASCADE, verbose_name="出版社")
        # ManyToManyField多对多
        authors = models.ManyToManyField(AuthorInfo, verbose_name="图书作者")
    
        class Meta:
            db_table = "db_book_info"
            verbose_name = "图书信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.title
    
    
  2. 创建urls.py

    from django.urls import re_path
    from .views import BookView
    
    urlpatterns = [
      	# restapi风格定制路由
        re_path(r"^books/$", BookView.as_view()),
    ]
    
    
  3. 创建views.py

    1. 导入模块

      # 第一步: 导入模块
      from rest_framework import serializers
      
    2. 建立序列化类

      class BookSerializer(serializers.ModelSerializer):
          class Meta:
              # 指定    要操作的模型类
              model = BookInfo
      
              # 指定序列化的字段
              fields = (
                  "title",
                  "price",
                  "publishDate",
                  "publish",
                  "authors",
                  "author_list",
                  "publish_name",
                  "publish_city"
              )
      
              # 指定那些字段是只写的
              # write_only只写的 (只写的 前端发送数据时要写它, 后端返回数据时没有它)
              extra_kwargs = {
                  "publish": {"write_only": True},
                  "authors": {"write_only": True}
              }
      
          # 自定义的字段
          # read_only只读的 (只读的 前端发送数据时不用写它, 后端返回数据时有它)
          publish_name = serializers.CharField(max_length=32, read_only=True, source="publish.name")
          publish_city = serializers.CharField(max_length=32, read_only=True, source="publish.city")
      
          author_list = serializers.SerializerMethodField()
      
          def get_author_list(self, book_obj):
          	#  book_obj是BookInfo的对象
              # 拿到queryset开始循环 [ {}, {}, {}]
              authors = []
      				
              # book_obj.authors.all() 获取所有author对象
              for author in book_obj.authors.all():
                  authors.append(author.name)
              return authors
      
      
    3. 获取queryset/开始序列化/序列化后的数据, 返回给客户端

      from rest_framework.views import APIView
      # Response返回序列化对象
      from rest_framework.response import Response
      
      from .models import BookInfo, PublishInfo, AuthorInfo
      from .app_serializers import BookSerializer
      
      
      class BookView(APIView):
          def get(self, request):
              # 第三步: 获取queryset
              origin_data = BookInfo.objects.all()
      
              # 第四步: 开始序列化
              # 当序列化多条数据时 要加上many=True
              serialized_data = BookSerializer(origin_data, many=True)
      				
           # 返回序列化对象
              # 记住序列化的值在data属性里
              # 所以这里用serialized_data.data取序列化的值
              return Response(serialized_data.data)
          def post(self, request):
           # 接受前端发送的json数据
              client_data = request.data
      
              # many默认是False, 可以省略不写
              # 开始序列化
              verified_data = BookSerializer(data=client_data, many=False)
              # 判断序列化数据的合法性
              if verified_data.is_valid():
                  # 当执行save()直接保存到数据库
                  verified_data.save()
      
                  return Response(verified_data.data)
              else:
                  return Response(verified_data.errors)
      
      
    4. postman效果图
      在这里插入图片描述

序列化组件的使用及接口设计

  1. 请求接口设计get请求单个数据(restapi规范)

      GET						127.0.0.1:8000/books/			# 获取所有数据, 返回值:[{}, {}, {}]
      GET						127.0.0.1:8000/books/{id}       # 获取一条数据, 返回值:{}
      POST					    127.0.0.1:8000/books/			# 新增一条数据, 返回值:{}
      PUT						127.0.0.1:8000/books/{id}       # 修改一条数据, 返回值:{}
      DELETE                    127.0.0.1:8000/books/{id}       # 删除一条数据, 返回值: 空对象
    
  2. 创建model.py

    1. python manage.py makemigrations
    2. python manage.py migrate
  3. urls.py

  4. views.py

    1. 开始使用序列化

      1. 导入模块 from rest_framework import serializers

      2. 建立一个序列化类

        class BookSerializer(serializers.ModelSerializer):
          	字段可以自定义
        
      3. 获取queryset

        ​ book_obj = BookInfo.objects.get(id=1)

      4. 开始序列化

        serialized_data = BookSerializer(book_obj, many=False)

      5. 序列化后的数据, 返回给客户端

        return Response(serialized_data.data)

GET单个数据案例

  1. 创建模型类

    from django.db import models
    
    from datetime import datetime
    # from django.contrib.auth.models import AbstractUser
    
    
    class AuthorInfo(models.Model):
        name = models.CharField(max_length=32, verbose_name="作者名称")
        age = models.IntegerField(verbose_name="作者年龄")
    
        class Meta:
            db_table = "db_author_info"
            verbose_name = "作者信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class PublishInfo(models.Model):
        name = models.CharField(max_length=32, verbose_name="出版社名称")
        city = models.CharField(max_length=32, verbose_name="出版社所在城市")
        email = models.EmailField(verbose_name="出版社邮箱")
    
        class Meta:
            db_table = "db_publish_info"
            verbose_name = "出版社信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class BookInfo(models.Model):
        title = models.CharField(max_length=32, verbose_name="书名")
        publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")
    
        # max_digits小数位加整数位多少长度 decimal_places小数位长度为2
        price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")
        
        # on_delete
        # CASCADE:这就是默认的选项,级联删除,你无需显性指定它。
    		# PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。
    		# SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。
    		# SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
    		# SET(): 自定义一个值,该值当然只能是对应的实体了
        publish = models.ForeignKey(PublishInfo, related_name="book", related_query_name="book_query", on_delete=models.CASCADE, verbose_name="出版社")
        # ManyToManyField多对多
        authors = models.ManyToManyField(AuthorInfo, verbose_name="图书作者")
    
        class Meta:
            db_table = "db_book_info"
            verbose_name = "图书信息"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.title
    
    
  2. 创建urls.py

    from django.urls import re_path
    from .views import BookView
    
    urlpatterns = [
      	# restapi风格定制路由
        re_path(r"^books/(d+)/$", BookFilterView.as_view())
    ]
    
    
  3. 创建views.py

    1. 导入模块

      # 第一步: 导入模块
      from rest_framework import serializers
      
    2. 建立序列化类

      class BookSerializer(serializers.ModelSerializer):
          class Meta:
              # 指定    要操作的模型类
              model = BookInfo
      
              # 指定序列化的字段
              fields = (
                  "title",
                  "price",
                  "publishDate",
                  "publish",
                  "authors",
                  "author_list",
                  "publish_name",
                  "publish_city"
              )
      
              # 指定那些字段是只写的
              # write_only只写的 (只写的 前端发送数据时要写它, 后端返回数据时没有它)
              extra_kwargs = {
                  "publish": {"write_only": True},
                  "authors": {"write_only": True}
              }
      
          # 自定义的字段
          # read_only只读的 (只读的 前端发送数据时不用写它, 后端返回数据时有它)
          publish_name = serializers.CharField(max_length=32, read_only=True, source="publish.name")
          publish_city = serializers.CharField(max_length=32, read_only=True, source="publish.city")
      
          author_list = serializers.SerializerMethodField()
      
          def get_author_list(self, book_obj):
              # 拿到queryset开始循环 [ {}, {}, {}]
              authors = []
      				
              # book_obj.authors.all() 获取所有author对象
              for author in book_obj.authors.all():
                  authors.append(author.name)
              return authors
      
      
    3. 获取queryset/开始序列化/序列化后的数据, 返回给客户端

       from django.shortcuts import render
       from django.http import JsonResponse
       
       from rest_framework.views import APIView
       
       from rest_framework.response import Response
       
       from .models import BookInfo, PublishInfo, AuthorInfo
       from .app_serializers import BookSerializer
       
       class BookFilterView(APIView):
           def get(self, request, book_id):
               try:
                   book_obj = BookInfo
                                  
                                  版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
      原文链接:https://blog.csdn.net/zsx1314lovezyf/article/details/97267556
      站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢