django 데이터 API 인터페이스의 drf 변환

25467 단어 pythondjango
본고는 상품 목록 데이터 인터페이스를 예로 삼아 drf 모듈의 간편하고 강력한 점을 보여 준다.
실현되다
방식 1: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')

방법2:django:modelto_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')

방식3: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')

방식 4: django: Json Response
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 목록 구현
방법 1: 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)

페이지 나누기:
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
    

좋은 웹페이지 즐겨찾기