我通过过滤get_queryset 和get_object 解决了这个问题。有其他需要帮助的人的例子:
urls.py
url(r'(?P<profile_id>\d+)/albums/(?P<album_id>\d+)/images/(?P<image_id>\d+)/comments/(?P<comment_id>\d+)/?$',CommentDetailAPIView.as_view(), name='profile-album-image-comment'),
views.py
class GetCommentsAPI(ListAPIView):
"""
"""
serializer_class = CommentSerializer
filter_backends = [SearchFilter] # ово мора бити низ!
authentication_classes = [AllowAny]
def get_queryset(self, *args, **kwargs):
# ipdb.set_trace(context=5)
profile_id = self.kwargs.get("profile_id")
if not profile_id:
return Response({"status": "fail"}, status=403)
profile = Profile.objects.get(pk=profile_id)
album_id = self.kwargs.get("album_id")
if not album_id:
return Response({"status": "fail"}, status=403)
album = Album.objects.get(pk=album_id, owner_id=profile_id)
if not album:
return Response({"status": "fail"}, status=404)
image_id = self.kwargs.get("image_id")
if not image_id:
return Response({"status": "fail"}, status=403)
image = Image.objects.get(pk=image_id, album_id=album_id)
queryset_list = Comment.objects.filter(image__pk=image_id)
return queryset_list
class CommentDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView):
"""
"""
queryset = Comment.objects.all()
serializer_class = DetailedCommentSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def get_object(self):
profile_id = self.kwargs.get("profile_id")
profile = Profile.objects.get(pk=profile_id)
if not profile:
return JsonResponse({"status":"fail","code":404})
album_id = self.kwargs.get("album_id")
album = Album.objects.get(pk=album_id)
if not album:
return JsonResponse({"status": "fail", "code": 404})
image_id = self.kwargs.get("image_id")
image = Image.objects.get(pk=image_id)
if not image:
return JsonResponse({"status": "fail", "code": 404})
comment_id = self.kwargs.get("comment_id")
if not comment_id:
return JsonResponse({"status": "fail", "code": 404})
comment = get_object_or_404(queryset=Comment.objects.all(), pk=comment_id, image__pk=image_id)
return comment
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
当我完成项目时,我将在那里链接 repo。祝你好运!