• 特点:配合二级视图GenericAPIView来使用的
    • 作用:可以提供通用的增删改查功能,提供基本视图行为(列表视图、详情视图)的操作,但方法名不是get、post等,而是可以使用其他的方法名
    • 分类
      • ListModelMixin类:提供list方法,查询所有的数据(列表视图)
      • CreateModelMixin类,提供create方法,创建一条数据(列表视图)
      • RetrieveModelMixin类:提供retrieve方法,获取指定的一条数据(详情视图)
      • UpdateModelMixin类:提供update方法,更新指定的一条数据(详情视图)
      • DestoryModelMixin类:提供destory方法,删除指定的一条数据(详情视图)

        需要注意的是:配合使用时,视图类中的方法名依然是get、post、put、delete,不同的是在各个方法体内直接使用slef调用mixins中对应类提供的行为方法,列表视图把request作为参数传入即可,详情视图把request和id作为参数传递即可,不需要其他的操作,所有的操作都已经被封装在对应的方法内

    1. from rest_framework.generics import GenericAPIView
    2. from rest_framework.response import Response
    3. from rest_framework import status
    4. from rest_framework import mixins
    5. from .models import UserProfile
    6. from .serializers import UserProfileSerializers
    7. class UserListMixinGenericAPIView(GenericAPIView,
    8. mixins.ListModelMixin,
    9. mixins.CreateModelMixin):
    10. """ genericAPIView和Mixin配合创建列表视图 """
    11. queryset = UserProfile.objects.all()
    12. serializer_class = UserProfileSerializers
    13. lookup_url_kwarg = 'id'
    14. def get(self, request, *args, **kwargs):
    15. return self.list(request)
    16. def post(self, request, *args, **kwargs):
    17. return self.create(request)
    18. class UserDetailMixinGenericAPIView(GenericAPIView,
    19. mixins.RetrieveModelMixin,
    20. mixins.UpdateModelMixin,
    21. mixins.DestroyModelMixin):
    22. """ 详情视图 """
    23. queryset = UserProfile.objects.all()
    24. serializer_class = UserProfileSerializers
    25. lookup_url_kwarg = 'id'
    26. def get(self, request, id):
    27. return self.retrieve(request, id)
    28. def put(self, request, id):
    29. return self.update(request, id)
    30. def delete(self, request, id):
    31. return self.destroy(request, id)