DRF序列化之APIView

DRF官网文档:https://www.django-rest-framework.org/

前面我们学习了什么是DRF、并通过原生Django实现了后端数据序列化并返回JSON格式数据。既然通过Django就可以实现序列化、我们为什么还需要DRF呢?DRF的官方介绍是这样说的:

Django REST框架是用于构建Web API的功能强大且灵活的工具包。

您可能要使用REST框架的一些原因:

既然DRF这么强大,今天我们继续讲解如何通过DRF来实现序列化。DRF实现序列化的方式有很多种、比如通过APIView、ModelSerializer、GenericView等方式都可以实现序列化、下面我们就通过示例来看看这些方法的实现过程。

通过DRF APIView方式实现序列化

在开始之前我们需要安装DRF所需的插件(安装之前记得确认DRF、Django、Python的版本兼容性):

# 官网建议我们安装一下插件
PyYAML, uritemplate (5.1+, 3.0.0+) - Schema generation support.
Markdown (3.0.0+) - Markdown support for the browsable API.
Pygments (2.4.0+) - Add syntax highlighting to Markdown processing.
django-filter (1.0.1+) - Filtering support.
django-guardian (1.1.1+) - Object level permissions support.

# 这里我们先安装下面3个插件、后续有用到的再来安装
# 网速慢的可以通过-i https://pypi.douban.com/simple来加速
pip install djangorestframework
pip install markdown
pip install django-filter

安装完成之后我们需要到settings.py文件里面添加INSTALLED_APPS中:

INSTALLED_APPS = [
   ......
    'rest_framework',
   ......]

然后我们就可以来准备Views文件了(可以参考官网文档:https://www.django-rest-framework.org/tutorial/3-class-based-views/):

from .models import Goods
from goods.serializers import GoodsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response


# Create your views here.
class GoodsList(APIView):
    """
   商品列表
   """

    def get(self, request, format=None):
        goods = Goods.objects.all()[:10]
        goods_serializer = GoodsSerializer(goods, many=True)
        return Response(goods_serializer.data)

    def post(self, request, format=None):
        pass
        # serializer = SnippetSerializer(data=request.data)
        # if serializer.is_valid():
        #     serializer.save()
        #     return Response(serializer.data, status=status.HTTP_201_CREATED)
        # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

通过上面的代码我们通过DRF引入了一个GoodsSerializer类、这里我们需要去对应的APP目录下创建一个serializers.py文件(这里我们也可以参考官网文档:https://www.django-rest-framework.org/tutorial/1-serialization/):

from rest_framework import serializers


class GoodsSerializer(serializers.Serializer):
    goods_sn = serializers.CharField(max_length=50)
    name = serializers.CharField(max_length=300,)
    click_num = serializers.IntegerField(default=0)

注:我们这样做的目的是为了在serializers的时候映射所有的ORM字段,以及在POST返回的时候直接通过serializers的Serializer方法把数据报错到数据库中(类似Django的FORM功能)。

这里我们为了方便测试、只写了3个字段进行序列化;我们启动项目并访问Http://127.0.0.1:8000/goods接口、可以看到数据已经正常返回。而且我们也可以点击GET按钮选择返回的数据格式类型是API或者JSON格式。

imgimg

点击OPTIONS我们也可以看到接口的描述信息,比如接口的name、description、renders(返回数据格式类型)、parses(数据解析类型)等信息。

img

推荐文章

10条评论

  1. When some one searches for his necessary thing, so he/she wishes to be available that in detail, thus that thing is maintained over here. Inez Bertrand Saleem

  2. I got what you mean,saved to favorites, very nice internet site. Nessy Stillmann Lovell

  3. Google fait appel. Elle est disponible sur iOS et Android. Ulrike Jonas Isaac

  4. I enjoyed reading this. You appear to know a lot about this. Thanks for writing this. I really like your article. Wylma Bartholemy Chisholm

  5. But wanna comment that you have a very decent internet site , I the pattern it really stands out. Arliene Fonsie Thaddus

  6. Some really select content on this website , saved to bookmarks . Brenn Crosby Yasmin

  7. Touche. Solid arguments. Keep up the great spirit. Glynis Nathan Ainsworth

  8. Everything is very open with a precise description of the challenges. It was truly informative. Your website is very helpful. Many thanks for sharing! Jodee Stu Mylor

  9. I am glad to be a visitant of this pure web site! , thanks for this rare info ! . Sonni Andrey Lemal

  10. Thanks for reporting back. Airflow through the ducting is horrible, sharp curves, and a lot of restrictions. Anything that can be done to smooth out the airflow is significant. Ardeen Quinn Fulviah

评论已关闭。