Reputation: 1003
How it is possible to get foreign key assigned in url with Django REST Framework?
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)
My goal is to use this URL (urls.py):
url(r'^event/(?P<pk>[0-9]+)/comments', views.CommentList.as_view())
Somehow I managed to get foreign key with this way
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
But I don't know how to get foreign key with such URL using ''generics.ListCreateAPIView''
http://127.0.0.1:8000/event/<eventnumber>/comments
Upvotes: 2
Views: 1182
Reputation: 22697
If you want to get the pk. You can use lookup_url_kwarg
attribute from ListCreateAPIView
class.
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.
The default value for lookup_field
attribute is 'pk'
. So, if you change your url keyword argumento from another different to pk, you should define lookup_url_kwarg
then.
class CommentLikeList(ListCreateAPIView):
lookup_url_kwarg = 'eventnumber'
You can inspect all DRF classes methods and attributes over here: http://www.cdrf.co/
Upvotes: 2