django-rest-framework视图
GenericView
class GenericView(GenericAPIView):
queryset = models.Role.objects.all()
serializer_class = serializers.RoleSerializer
pagination_class = PageNumberPagination
def get(self, request):
# 获取数据
data = self.get_queryset()
# 获取分页数据
page_data = self.paginate_queryset(data)
# 获取序列化数据
resp = self.get_serializer(instance=page_data, many=True)
return Response(resp.data)
- GenericView在原来的ApiView上做了一点封装,主要使用的有三个方法
get_queryset
: 获取查询的queryset对象paginate_queryset
: 获取分页后的对象,需要接受一个queryset对象参数get_serializer
: 序列化数据,制定序列化对象和制定many的参数
GenericViewSet
class GenericView(GenericViewSet):
def list(self, request):
return Response('list')
from django.conf.urls import re_path
from . import views
urlpatterns = [
re_path(r'^index/', views.GenericView.as_view({'get': 'list'})),
]
- GenericViewSet的使用跟GenericView大致无差别,只是对应请求方法的函数需要自定义
- url的as_view方法需要传递一个字典参数,字典的key就是对应的请求方法,value就是对应请求方法的处理函数
ModelViewSet
class GenericView(ModelViewSet):
queryset = models.Role.objects.all()
serializer_class = serializers.RoleSerializer
pagination_class = PageNumberPagination
- ModelViewSet就更高级了,它默认实现了增删该查的方法,只需要配置好对应的属性就可以了
url
from django.conf.urls import re_path
from . import views
urlpatterns = [
re_path(r'^index/', views.GenericView.as_view({'get': 'list', 'post': 'update'})),
]
全自动生成路由
from django.urls import path, include, re_path
from rest_framework import routers
from . import views
route = routers.DefaultRouter()
route.register('index', views.GenericView)
urlpatterns = [
re_path('', include(route.urls))
]