django数据API接口之drf演变

本文以商品列表数据接口为例,展示了drf模块的便捷、强大之处。

django实现

方式一:django自带的view

from django.views.generic.base import View
from goods.models import Goods
from django.http import HttpResponse
import json

class GoodListView(View):
    def get(self, request):
        """
        通过django的view实现商品列表
        :param request
        :return
        """
        json_list = []
        goods = Goods.objects.all()[:10]
        for good in goods:
            json_dict = {}
            json_dict['name'] = good.name
            json_dict['category'] = good.category.name
            json_dict['market_price'] = good.market_price
            json_list.append(json_dict)
        return HttpResponse(json.dumps(json_list), content_type='application/json')

方式二: django: model_to_dict

from django.views.generic.base import View
from goods.models import Goods
from django.http import HttpResponse
import json
from django.forms.models import model_to_dict

class GoodListView(View):
    def get(self, request):
        """
        通过django的view实现商品列表
        :param request
        :return
        """
        json_list = []
        goods = Goods.objects.all()[:10]


        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        return HttpResponse(json.dumps(json_list), content_type='application/json')

方式三: django: serializers

from django.views.generic.base import View
from goods.models import Goods
from django.http import HttpResponse
import json
from django.core import serializers

class GoodListView(View):
    def get(self, request):
        """
        通过django的view实现商品列表
        :param request
        :return
        """
        json_list = []
        goods = Goods.objects.all()[:10]
        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)
        return HttpResponse(json.dumps(json_data), content_type='application/json')

方式四: django: JsonResponse

from django.views.generic.base import View
from goods.models import Goods
from django.http import JsonResponse
import json
from django.core import serializers

class GoodListView(View):
    def get(self, request):
        """
        通过django的view实现商品列表
        :param request
        :return
        """
        goods = Goods.objects.all()[:10]
        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)
        return JsonResponse(json_data, safe=False)

drf 实现goods列表

方式一: APIView + serializers.Serializer

from rest_framework.views import APIView
from rest_framework import serializers

class GoodsSerializer(serializers.Serializer):
    name = serializers.CharField(required=True, max_length=100)
    click_num = serializers.IntegerField(default=0)
	

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

APIView + serializers.Serializer 创建goods

from rest_framework.views import APIView
from rest_framework import serializers

class GoodsSerializer(serializers.Serializer):
    name = serializers.CharField(required=True, max_length=100)
    click_num = serializers.IntegerField(default=0)
	def create(self, validated_data):
        """
        Create and return a new 'good' instance, given the validated data.
        """
        return Goods.objects.create(**validated_data)

class Goods1ListView(APIView):
    '''List'''
    def get(self, request, format=None):
        goods = Goods.objects.all()[:10]
        goods_serializer = GoodsSerializer(goods, many=True)
	
	def post(self, request, format=None):
        serializer = Goods1Serializer(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)

改为serializers.ModelSerializer

class Goods1Serializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ['id', 'click_num', 'add_time', 'market_price']

序列化嵌套:

class Category1Serializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'

class Goods1Serializer(serializers.ModelSerializer):
    category = Category1Serializer()

    class Meta:
        model = Goods
        fields = '__all__'

mixins + generics:

class Goods1ListView(mixins.ListModelMixin, generics.GenericAPIView):
    """
    商品列表页
    """
    queryset = Goods.objects.all()[:10]
    serializer_class = Goods1Serializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

pagination分页:

class GoodsPagination(PageNumberPagination):
    """
    商品 - 自定义分页
    """
    page_size = 12
    page_size_query_param = 'page_size'
    page_query_param = 'page'
    max_page_size = 100
   
class Goods1ListView(mixins.ListModelMixin, generics.GenericAPIView):
    # 分页类
    pagination_class = GoodsPagination
    

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