【问题标题】:Django REST framework foreign key with generics.ListCreateAPIView带有generics.ListCreateAPIView的Django REST框架外键
【发布时间】:2016-10-05 19:39:42
【问题描述】:

如何使用 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)

我的目标是使用这个 URL (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

【问题讨论】:

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


    【解决方案1】:

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

    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 更改为 pk,那么您应该定义 lookup_url_kwarg

    class CommentLikeList(ListCreateAPIView):
        lookup_url_kwarg = 'eventnumber'
    

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

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 2021-12-09
      • 2014-09-11
      • 1970-01-01
      • 2018-10-09
      • 2019-05-01
      • 2015-05-10
      • 2023-03-17
      相关资源
      最近更新 更多