Django REST框架外键与generics.ListCreateAPIView

时间:2016-10-05 19:39:42

标签: python django generics foreign-keys django-rest-framework

如何使用Django REST Framework在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)

我的目标是使用此网址(urls.py):

url(r'^event/(?P<pk>[0-9]+)/comments', views.CommentList.as_view())

不知何故,我设法以这种方式获得外键

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

但我不知道如何使用这样的URL获取外键 '' generics.ListCreateAPIView ''

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

1 个答案:

答案 0 :(得分:1)

如果你想获得pk。您可以使用lookup_url_kwarg类的ListCreateAPIView属性。

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 - 应该用于的URL关键字参数   对象查找。 URL conf应包含关键字参数   对应于此值。如果未设置,则默认使用相同的   值为lookup_field。

lookup_field属性的默认值为'pk'。因此,如果您将url关键字参数从另一个不同更改为pk,则应定义lookup_url_kwarg

class CommentLikeList(ListCreateAPIView):
    lookup_url_kwarg = 'eventnumber'

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