我正在编写我的学校项目,构建Django Rest API。我有下一个实体:Profiles
,Albums
,Images
,Comments
,Likes
。
我想要的是以这种方式使资源可访问:
api/v1/profiles/1/albums
- >从id为
在我发现的例子中,有ViewSet
使用,而不是APIView
我想使用(我真的是新手,我甚至不知道我可以使用ViewSet
CRUID运营)。
我试着实施下一步:
和其他许多人一样,但我无法让它发挥作用......
如果有一些详细的教程,请参考它,我真的需要快速。
谢谢大家!
答案 0 :(得分:1)
可能需要extra-link-and-actions,例如:
from rest_framework.decorators import detail_route
class ProfileView
# Your Code Here
@detail_route(methods=['GET'])
def albums(request, pk=None):
# Heed to change related name 'albums_set'
qs = self.get_object().albums_set.all()
serializer = AlbumsSerializer(qs, many=True)
return Response(serializer.data)
答案 1 :(得分:1)
我通过过滤get_queryset
和get_object
完成了此问题。其他人需要帮助就有一个例子:
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'),
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)
当我完成项目时,我会在那里链接回购。祝你好运!