django-rest-framework序列化的使用(一)

一、关于django-rest-framework环境的配置

  • 1、官网地址下查看支持的django版本及安装几个主要的包

    pip install coreapi
    pip install Markdown
    pip install django-filter
    pip install django-crispy-forms
    pip install django-guardian
  • 2、利用pycharm创建一个django项目

  • 3、setting.py的基本配置

    • 1、配置编码

      
      #!/usr/bin/env python
      
      
      # encoding: utf-8
      
    • 2、修改国内时间及支持中文

      
      #设置时区  
      
      LANGUAGE_CODE = 'zh-hans'  #中文支持,django1.8以后支持;1.8以前是zh-cn
      TIME_ZONE = 'Asia/Shanghai'
      USE_I18N = True
      USE_L10N = True
      USE_TZ = False   #默认是Ture,时间是utc时间,由于我们要用本地时间,所用手动修改为false
    • 3、配置mysql数据库引擎

      
      # 配置数据库 
      
      DATABASES = {
          'default': {
              'ENGINE': 'django.db.backends.mysql',
              'NAME': 'vueshop',
              'USER': 'root',
              'PASSWORD': "root",
              'HOST': "127.0.0.1",
              'OPTIONS': {'init_command': 'SET storage_engine=INNODB;'}  # 数据库引擎
          }
      }
    • 4、把rest_framework加入到注册的app

    • 5、在urls.py中配置下

      from django.conf.urls import url, include
      from rest_framework.documentation import include_docs_urls
      urlpatterns = [
          ....
          url(r'^api-auth/', include('rest_framework.urls')),
          url(r'docs/', include_docs_urls(title='接口学习'))
      ]

二、使用APIView创建返回第一个接口

  • 1、关于serializers的认识

    在传统的使用模板开发中我相信我们一个app里面都会创建一个forms.py的文件,来校验客户端传递过来的数据,serializers则是django-rest-framework封装了一层类似forms.py的功能,只是对json的校验

  • 2、书写一个serializers(字段要和models.py中保持一致,一个app下一个serializers.py文件)

    from rest_framework import serializers
    
    
    class GoodsSerializer(serializers.Serializer):
        name = serializers.CharField(required=True, max_length=100)
        click_num = serializers.IntegerField(default=0)
  • 3、定义view继承APIView

    from .serializers import GoodsSerializer
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from .models import Goods
    
    
    class GoodsListView(APIView):
        def get(self, request, format=None):
            goods = Goods.objects.all()[:10] # 只查询10条数据 
            goods_serializer = GoodsSerializer(goods, many=True)
            return Response(goods_serializer.data)
    
  • 4、配置url

    from goods.views import GoodsListView
    urlpatterns = [
        url(r'^goods/$', GoodsListView.as_view()),
        url(r'^api-auth/', include('rest_framework.urls')),
        url(r'docs/', include_docs_urls(title='接口测试学习'))
    ]

三、前端使用post提交数据,保存到数据库中

  • 1、在serializers.py中添加一个create的函数

    class GoodsSerializer(serializers.Serializer):
        name = serializers.CharField(required=True, max_length=100)
        click_num = serializers.IntegerField(default=0)
        market_price =serializers.FloatField(default=0)
    
        def create(self, validated_data):
            """
            validated_data会把上面全部的字段接收
            """
            return Goods.objects.create(**validated_data)
  • 2、视图层使用post

    from rest_framework import status
    class GoodsListView(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):
            serializer = GoodsSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data,status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    

四、使用ModelSerializer来书写serializer

  • 1、书写serializer

    from rest_framework import serializers
    from .models import Goods
    class GoodsSerializersModel(serializers.ModelSerializer):
        """
        使用ModelSerializer更加简便的返回自己想要的字段
        """
        class Meta:
            model = Goods
            fields = ('name', 'click_num', 'market_price', 'add_time')
  • 2、视图层跟上面APIView中一样的写

  • 3、url也跟上面APIViewgoods的一样

五、使用ModelSerializer如果要返回全部的字段

  • 1、修改上面的serializer

    class GoodsSerializersModel(serializers.ModelSerializer):
        """
        使用ModelSerializer更加简便的返回自己想要的字段
        """
        class Meta:
            model = Goods
            # fields = ('name', 'click_num', 'market_price', 'add_time')
            fields = '__all__'
  • 2、其它的都保持不变

六、注意到上面返回的json外键都是一个id并没有把外键关联的表的数据也返回

  • 1、序列化外键的表

    class CategorySerializer(serializers.ModelSerializer):
        """
        序列化分类表
        """
        class Meta:
            model = GoodsCategory
            fields = '__all__'
    
  • 2、在别的serializers中实例化

    class GoodsSerializersModel(serializers.ModelSerializer):
        """
        使用ModelSerializer更加简便的返回自己想要的字段
        """
        # 实例化上面的分类表的序列号
        category = CategorySerializer()
        class Meta:
            model = Goods
            # fields = ('name', 'click_num', 'market_price', 'add_time')
            fields = '__all__'
    

你可能感兴趣的:(python,django)