[英]Use one class based view for both List and Retrieve Rest API
I currently have two different class based views for detailing a specific object and for listing all objects:我目前有两个不同的基于类的视图,用于详细说明特定对象和列出所有对象:
class StatusList(ListAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
class StatusDetail(RetrieveAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
Note that helperfunctions.getObjects() simply returns the objects that share the same establishment with the user, so that they can't see statuses that they shouldn't.请注意,helperfunctions.getObjects() 仅返回与用户共享同一机构的对象,因此他们看不到他们不应该看到的状态。
What I want to know is whether there's an option to use only one class based view for both StatusDetail and StatusList, which would automatically know that when it gets a pk in the get request it returns the appropriate object, and when it doesn't, it should return the whole list of objects.我想知道的是,是否可以选择仅对 StatusDetail 和 StatusList 使用一个基于类的视图,它会自动知道当它在 get 请求中获得一个 pk 时,它会返回适当的对象,而当它没有时,它应该返回整个对象列表。
Thanks for any help :)谢谢你的帮助 :)
Use viewsets , like so :使用视图集,如下所示:
from rest_framework import viewsets, permissions, mixins
class StatusDetail(mixins.ListModelMixin, #specify wanted mixins
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
Okay so I got to this awesome, clean solution with the help of the comments of Gahan and Daniel Roseman :好的,在Gahan和Daniel Roseman的评论的帮助下,我得到了这个很棒、干净的解决方案:
class StatusViewSet(ModelViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
And added a router to the urlpatterns:并在 urlpatterns 中添加了一个路由器:
router = routers.SimpleRouter()
router.register(r'status', views.StatusViewSet, base_name='Status')
urlpatterns = router.urls
Thank you all very much!非常感谢大家!
Viewsets has ReadOnlyModelViewSet
and allows only retrieve
and list
. Viewsets 有ReadOnlyModelViewSet
并且只允许retrieve
和list
。
class StatusDetail(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.