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