django - APIView和Model ViewSet在使用或继承上有什么区别

标签 django django-views django-rest-framework

当我想序列化我的模型以获取它们的对象/记录列表时,我会遇到关于何时使用 APIView 和何时使用 ModelViewSet 的区别?

例如,在 APIView documentation我们有 ListUser 类和他们的 get 方法,我们可以得到用户列表

class ListUsers(APIView):
    """
    View to list all users in the system.

    * Requires token authentication.
    * Only admin users are able to access this view.
    """
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,)

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames) 

我已经通过这种方式使用 ModelViewSet 获得了相同的用户列表:
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', )

如何确定何时应使用 APIView 或 ModelViewSet 执行此任务?

最佳答案

问题太开放了,尽管我会尝试回答。

第一件事,APIViewViewSet与模型无关,而 ModelViewSet , GenericAPIView , ListAPIView (和合作)是。

*View 和 *ViewSet 之间的主要区别在于 *ViewSet 旨在与路由器一起使用并提供一个类来公开资源,而 *View 需要两个(一个用于列表/创建,另一个用于详细信息/更新/删除)。

请注意 APIView是最低级别,仅与 HTTP 动词 (get/post/put...) 相关,而 ViewSetGenericAPIView将有 CRUD,例如列表/更新...

为了公开 Django 的模型,您需要

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

或者
class UserListCreateView(ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

关于django - APIView和Model ViewSet在使用或继承上有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878524/

相关文章:

python - Django 中的日期验证错误

python - Django CKEditor 图片上传没有出现

python - 如何在 django shell 中打印出我的设置内容?

python - OAuth2 客户端(Python/Django)

django - 如何使用模拟数据测试 Stripe Webhook

python - 覆盖管理 View - Django

python - 显示经过身份验证的用户使用模型管理器创建的条目

django - 优化 Django 查询集相关比较

django - 使用 Django REST 框架进行批量插入的最佳设计模式是什么?

django - 如何在Django Rest Framework SimpleRouter上使斜杠为可选