django rest framework 演变

  • json
  • json + model_to_dict
  • json + serializers
class GoodsListView(View):
    def get(self, request):
        """
        通过Django的view实现商品列表页
        返回json字符串
        :param request: 
        :return: 
        """

        goods = Goods.objects.all()[:10]

        # version 1.0
        # json_list = []
        # 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)
        # import json
        # from django.http import HttpResponse
        # return HttpResponse(json.dumps(json_list), content_type='application/json')

        # version 1.1
        # import json
        # json_list = []
        # from django.forms.models import model_to_dict
        # 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')

        # version 1.2
        from django.core import serializers
        import json
        json_data = serializers.serialize('json', goods)
        json_list = json.loads(json_data)
        from django.http import JsonResponse
        return JsonResponse(json_list, safe=False)

APIView

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

#  # views.py
# # APIView
# class GoodsListView(APIView):
#     """
#     list all goods
#     """
#     def get(self, request):
#         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)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

ModelSerializer

class GoodsSerializer(serializers.ModelSerializer):
    category = CategorySerializer()  # 外键的嵌入

    class Meta:
        model = Goods
        fields = "__all__"

mixins generics

class GoodsPagination(PageNumberPagination):
    page_size = 12
    page_size_query_param = 'page_size'   # 可自定义每页取多少条数据 example http://127.0.0.1:8000/goods/?p=4&page_size=16
    page_query_param = 'page'
    max_page_size = 100


# mixins generics APIView
class GoodsListView(generics.ListAPIView):
    """
    list all goods
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination

ViewSet *****

class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    商品列表页   分页、搜索、过滤、排序
    """
    # order_by解决:UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list
    queryset = Goods.objects.order_by('id')   # 数据源
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    # authentication_classes = (TokenAuthentication,)
    # https://django-filter.readthedocs.io/en/master/
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)   # 过滤器
    search_fields = ('name', 'goods_brief', 'goods_desc')  # 搜索
    ordering_fields = ('sold_num', 'shop_price')   # 排序
    filter_class = GoodsFilter                   # 过滤

View层级关系

# GenericViewSet(viewset)     -- drf
#     GenericAPIView          -- drf
#         APIView             -- drf
#             View            -- django

Mixin层级关系

# Mixin
#   CreateModelMixin
#   ListModelMixin
#   UpdateModelMixin
#   RetrieveModelMixin
#   DestroyModelMixin

你可能感兴趣的:(django rest framework 演变)