问题描述
当我想序列化我的模型以获得它们的对象/记录的列表时,我会遇到关于何时使用 APIView 和何时使用 ModelViewSet 的差异?
I would meet the difference with respect to when use APIView and when use ModelViewSet when I want serialize my models with respect to get a list of their objects/records?
例如,在 APIView 文档中,我们有ListUser 类及其 get 方法我们可以获取用户列表
For example, in the APIView documentation we have that with the ListUser class and their get method we can get the list of users
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 获得了相同的用户列表:
I have been get this same list of users using ModelViewSet of this way:
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 来执行此任务?
How to can I identify when should I use APIView or ModelViewSet for this task?
推荐答案
问题太开放了,不过我会尽量回答.
Question is too open though I'll try to answer it.
首先,APIView
或 ViewSet
不与模型绑定,而 ModelViewSet
、GenericAPIView
、ListAPIView
(和 co)是.
First thing first, APIView
or ViewSet
aren't tied to models while ModelViewSet
, GenericAPIView
, ListAPIView
(and co) are.
*View 和 *ViewSet 之间的主要区别在于 *ViewSet 旨在与路由器一起使用并提供单个类来公开资源,而 *View 将需要两个(一个用于列表/创建,另一个用于详细信息/更新/删除).
The major difference between *View and *ViewSet is that *ViewSet are meant to work with routers and provide a single class to expose a Resource while *View will require two (one for list/create, another for detail/update/delete).
请注意,APIView
是最低级别,只会与 HTTP 动词(get/post/put...)相关联,而 ViewSet
或 GenericAPIView
会有 CRUD,例如 list/update...
Note that APIView
is the most lower level and will only tie to HTTP verbs (get/post/put...) while ViewSet
or GenericAPIView
will have CRUD such as list / update...
为了公开 Django 的模型,您需要
In order to expose a Django's Model, you'll need either
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
这篇关于APIView 和 Model ViewSet 使用或继承有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!