相关疑难解决方法(0)

在django休息框架中的泛型与视图集,如何更喜欢使用哪一个?

如何选择使用哪个泛型和视图集?换句话说,何时应该使用泛型,何时应该使用viewset来构建api.我知道它做同样的事情,但是viewset有路由器,所以在什么情况下泛型比viewset更好?

django django-rest-framework

16
推荐指数
2
解决办法
3700
查看次数

使用或继承APIView和Model ViewSet有什么区别

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

例如,在APIView 文档中,我们使用 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) 
Run Code Online (Sandbox Code Playgroud)

我已经通过这种方式使用 ModelViewSet 获得了相同的用户列表:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed …
Run Code Online (Sandbox Code Playgroud)

django django-views django-rest-framework

8
推荐指数
1
解决办法
4466
查看次数