Django REST framework foreign key with generics.ListCreateAPIView
<p>How it is possible to get foreign key assigned in url with Django REST Framework?</p>

<pre><code>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)
</code></pre>

<p>My goal is to use this URL (urls.py):</p>

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

<p>Somehow I managed to get foreign key with this way</p>

<pre><code>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
</code></pre>

<p>But I don't know how to get foreign key with such URL using 
''generics.ListCreateAPIView''</p>

<pre><code>http://127.0.0.1:8000/event/&lt;eventnumber&gt;/comments
</code></pre>

<p>If you want to get the pk. You can use <code>lookup_url_kwarg</code> attribute from <code>ListCreateAPIView</code> class.</p>

<pre><code>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)
</code></pre>

<blockquote>
  <p>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.</p>
</blockquote>

<p>The default value for <code>lookup_field</code> attribute is <code>'pk'</code>. So, if you change your url keyword argumento from another different to pk, you should define <code>lookup_url_kwarg</code> then.  </p>

<pre><code>class CommentLikeList(ListCreateAPIView):
    lookup_url_kwarg = 'eventnumber'
</code></pre>

<p>You can inspect all DRF classes methods and attributes over here:
<a href="http://www.cdrf.co/" rel="nofollow">http://www.cdrf.co/</a></p>

python django generics foreign-keys django-rest-framework