django 多种视图view继承方式
1. APIVIEW
继承django view,基于类视图,区别与基于方法视图
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
class ListUsers(APIView):
"""
View to list all users in the system.
* Requires token authentication.
* Only admin users are able to access this view.
"""
def get(self, request, format=None):
"""
Return a list of all users.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
def put((self, request, format=None):
pass
2. GenericAPIView
继承于APIVIEW,继承自APIVIew,增加了对于列表视图和详情视图可能用到的通用支持方法。通常使用时,可搭配一个或多个Mixin扩展类
子类:
. CreateAPIView
. ListAPIView
. RetrieveAPIView
. DestroyAPIView
. UpdateAPIView
…
支持定义的属性:
列表视图与详情视图通用
queryset 列表视图的查询集
serializer_class 视图使用的序列化器
- 列表视图使用:
pagination_class 分页控制类
filter_backends 过滤控制后端 - 详情页视图使用:
lookup_field 查询单一数据库对象时使用的条件字段,默认为’pk’
lookup_url_kwarg 查询单一数据时URL中的参数关键字名称,默认与look_field相同
from rest_framework.mixins import ListModelMixin
from django_filters.rest_framework import DjangoFilterBackend
class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 10000
class BookView(ListModelMixin,mixins.CreateModelMixin, GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
filter_backends = filter_backends = (DjangoFilterBackend,)
filter_fields = ('category', 'in_stock')
#或者查询
search_fields = ('username', 'email')
#分页
pagination_class = LargeResultsSetPagination
def get(self, request):
return self.list(request)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
---------------------------------------------------------
url(r"books/$",views.BookView.as_view()),
3. Mixins
- ListModelMixin
- CreateModelMixin
class BookDetailView(RetrieveModelMixin, GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request, pk):
return self.retrieve(request)
- RetrieveModelMixin
- UpdateModelMixin
- DestroyModelMixin
4. viewset
ViewSet视图集类不再实现get()、post()等方法,而是实现动作 action 如 list() 、create() 等通过as_view
class UserViewSet(viewsets.ViewSet):
"""
Example empty viewset demonstrating the standard
actions that will be handled by a router class.
If you're using format suffixes, make sure to also include
the `format=None` keyword argument for each action.
"""
def list(self, request):
pass
def create(self, request):
pass
def retrieve(self, request, pk=None):
pass
def update(self, request, pk=None):
pass
def partial_update(self, request, pk=None):
pass
def destroy(self, request, pk=None):
pass
----------------------------------
url 设置
user_list = UserViewSet.as_view({'get': 'list'})
user_detail = UserViewSet.as_view({'get': 'retrieve'})
或者
from myapp.views import UserViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet, base_name='user')
urlpatterns = router.urls