热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Django里rest_framework的视图组件generics进行优化视图

使用视图组件进行接口优化 使用视图组件的generics进行接口逻辑优化 导入generics from rest_framework import generics 定义序列化类 class

使用视图组件进行接口优化


  1. 使用视图组件的generics进行接口逻辑优化

    1. 导入generics

      from rest_framework import generics

    2. 定义序列化类

      class BookSerializer(serializers.ModelSerializer):class Meta:model = 指定模型类fields = (指定验证字段)extra_kwargs = {"field_name":{"write_only":True}}

    3. 导入序列化类

      from .app_serializers import BookSerializer

    4. 定义视图类

      # 如果你的类只需要get和post方法你继承generics.ListCreateAPIView就可以了
      class BookView(generics.ListCreateAPIView):# queryset和serializer_class是固定的写法# 指定querysetqueryset = BookInfo.objects.all()# 指定序列化类serializer_class = BookSerializer


GET获取全部数据和POST新增一条数据案列


  1. 建立url

    re_path(r"^books/$", BookView.as_view()),

  2. 建立model

    from django.db import modelsfrom datetime import datetime
    # from django.contrib.auth.models import AbstractUserclass 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_namedef __str__(self):return self.nameclass 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_namedef __str__(self):return self.nameclass BookInfo(models.Model):title = models.CharField(max_length=32, verbose_name="书名")publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")# max_digits小数位加整数位多少长度 decimal_places小数位长度为2price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")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_namedef __str__(self):return self.title

  3. 导入generics

    from rest_framework import generics

  4. 定义序列化类

    from.models import BookInfo
    # 第一步: 导入模块
    from rest_framework import serializersclass 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 = []for author in book_obj.authors.all():authors.append(author.name)return authors

  5. 导入序列化类

    from .app_serializers import BookSerializer

  6. 定义视图类

    from rest_framework import genericsfrom .models import BookInfo, PublishInfo, AuthorInfo
    from .app_serializers import BookSerializerclass BookView(generics.ListCreateAPIView):# GenericAPIView会帮我们去找queryset和serializer_class# queryset和serializer_class是固定的写法# 告诉它quertset是谁queryset = BookInfo.objects.all()# 告诉它序列化的类serializer_class = BookSerialize

  7. postman的GET请求所有数据
    在这里插入图片描述

  8. postman的POST请求所有数据
    在这里插入图片描述


使用视图组件进行接口优化


  1. 使用视图组件的generics进行接口逻辑优化

    1. 导入generics

      from rest_framework import generics

    2. 定义序列化类

      class BookSerializer(serializers.ModelSerializer):class Meta:model = 指定模型类fields = (指定验证字段)extra_kwargs = {"field_name":{"write_only":True}}

    3. 导入序列化类

      from .app_serializers import BookSerializer

    4. 定义视图类

      # 如果你的类只需要get和post方法你继承generics.ListCreateAPIView就可以了
      class BookFilterView(generics.RetrieveUpdateDestroyAPIView):# queryset和serializer_class是固定的写法# 指定querysetqueryset = BookInfo.objects.all()# 指定序列化类serializer_class = BookSerializer


GET获取一条数据和PUT修改一条数据和DELETE删除一条数据案列


  1. 建立url

    re_path(r"^books/(?P\d+)/$", BookFilterView.as_view())

  2. 正则不取名叫pk会报一个Expected view BookFilterView to be called with a URL keyword argument named “pk”.的错误
    在这里插入图片描述

  3. 建立model

    from django.db import modelsfrom datetime import datetime
    # from django.contrib.auth.models import AbstractUserclass 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_namedef __str__(self):return self.nameclass 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_namedef __str__(self):return self.nameclass BookInfo(models.Model):title = models.CharField(max_length=32, verbose_name="书名")publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")# max_digits小数位加整数位多少长度 decimal_places小数位长度为2price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")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_namedef __str__(self):return self.title

  4. 导入generics

    from rest_framework import generics

  5. 定义序列化类

    from.models import BookInfo
    # 第一步: 导入模块
    from rest_framework import serializersclass 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 = []for author in book_obj.authors.all():authors.append(author.name)return authors

  6. 导入序列化类

    from .app_serializers import BookSerializer

  7. 定义视图类

    from rest_framework import generics
    from .models import BookInfo, PublishInfo, AuthorInfo
    from .app_serializers import BookSerializer# 需要回去一条数据和删除一条数据和修改一条数据就继承它RetrieveUpdateDestroyAPIView
    class BookFilterView(generics.RetrieveUpdateDestroyAPIView):# GenericAPIView会帮我们去找queryset和serializer_class# queryset和serializer_class是固定的写法# 告诉它quertset是谁queryset = BookInfo.objects.all()# 告诉它序列化的类serializer_class = BookSerializer

8. postman的GET请求获取一条数据![在这里插入图片描述](https://img-blog.csdnimg.cn/20190725194302119.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDEzMTRsb3Zlenlm,size_16,color_FFFFFF,t_70)
9. postman的PUT请求修改一条数据![在这里插入图片描述](https://img-blog.csdnimg.cn/20190725194323649.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDEzMTRsb3Zlenlm,size_16,color_FFFFFF,t_70)

  1. postman的DELETE请求删除一条数据
    在这里插入图片描述

推荐阅读
author-avatar
真实的独孤一剑
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有