1.定义View
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.parsers import JSONParser from rest_framework import mixins, generics from rest_framework.generics import ListAPIView from rest_framework.pagination import PageNumberPagination from goods.models import Goods, GoodsCategory from goods.serializer import GoodsSerializer, CategorySerializer from rest_framework import viewsets from django_filters.rest_framework import DjangoFilterBackend import django_filters from rest_framework import filters class GoodsCategotyList(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = GoodsCategory.objects.all().filter(category_type=1) serializer_class = CategorySerializer
2.定义Serializer
from rest_framework import serializers from goods.models import Goods, GoodsCategory class CategorySerializer3(serializers.ModelSerializer): class Meta: model = GoodsCategory fields = '__all__' class CategorySerializer2(serializers.ModelSerializer): sub_cat = CategorySerializer3(many=True,read_only=True) class Meta: model = GoodsCategory fields = '__all__' class CategorySerializer(serializers.ModelSerializer): sub_cat = CategorySerializer2(many=True,read_only=True) # many必须指明 class Meta: model = GoodsCategory fields = '__all__'
3.配置urls
from django.urls import path, include import users.urls as userurl from django.conf.urls import url from django.views.static import serve from MxShop.settings import MEDIA_ROOT from goods.views_base import GoodsListView from rest_framework.documentation import include_docs_urls from rest_framework.routers import DefaultRouter from goods.views import GoodsList,GoodsCategotyList #,CategoryList router = DefaultRouter() router.register('goods',GoodsList,base_name='a') router.register('categorys',GoodsCategotyList) # goods_list = GoodsListSet.as_view({ # 'get':'list' # }) urlpatterns = [ # path('admin/', admin.site.urls), url(r'useradmin/', include(userurl)), url(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}), url(r'^docs/',include_docs_urls(title='drf文档')), url(r'^api-auth/', include('rest_framework.urls',namespace='rest_framework')), # url(r'^goods/$', goods_list, name="goods-list"), url(r'^',include(router.urls)), #url(r'^category/$',CategoryList.as_view()) ]
4.test