【发布时间】:2017-06-12 05:21:20
【问题描述】:
当我想序列化我的模型以获取其对象/记录列表时,我会遇到关于何时使用 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 来执行此任务?
【问题讨论】:
-
除了使用示例类进行比较外,以下是此问题的可能重复项:stackoverflow.com/questions/41379654/… 和 stackoverflow.com/questions/49482453/…
标签: django django-views django-rest-framework