Django REST框架外键泛型.ListCreateAPIVi

2024-06-25 06:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Django REST框架在url中分配外键?在

class CommentList(generics.ListCreateAPIView):
    serializer_class = CommentSerializer
    pagination_class = StandardResultsSetPagination
    queryset = Comment.objects.all()
    def get(self, *args, **kwargs):
        serializer = CommentSerializer(comment, many=True)
        return super(CommentList, self).get(*args, **kwargs)

我的目标是使用这个URL(网址.py)公司名称:

^{pr2}$

不知怎么的,我用这种方法得到了外键

class CommentLikeList(APIView):
    def get(self, request, *args, **kwargs):
        key = self.kwargs['pk']
        commentLikes = CommentLike.objects.filter(pk=key)
        serializer = CommentLikeSerializer(commentLikes, many=True)
        return Response(serializer.data)
    def post(self):
        pass

但是我不知道如何使用 ''泛型.ListCreateAPIView''

http://127.0.0.1:8000/event/<eventnumber>/comments

Tags: selftruegetreturnobjectsdefargskwargs
1条回答
网友
1楼 · 发布于 2024-06-25 06:56:04

如果你想得到pk。{{cd2>你可以使用

class CommentLikeList(ListCreateAPIView):

    def get(self, request, *args, **kwargs):
        key = self.kwargs[self.lookup_url_kwarg]
        commentLikes = CommentLike.objects.filter(pk=key)
        serializer = CommentLikeSerializer(commentLikes, many=True)
        return Response(serializer.data)

lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field.

lookup_field属性的默认值是'pk'。因此,如果您将url关键字argumento从另一个不同的改为pk,那么您应该定义lookup_url_kwarg。在

^{pr2}$

您可以在这里检查所有的DRF类方法和属性: http://www.cdrf.co/

相关问题 更多 >