Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture parameters in django-rest-framework

suppose this url:

http://localhost:8000/articles/1111/comments/ 

i'd like to get all comments for a given article (here the 1111).

This is how i capture this url:

url(r'^articles/(?P<uid>[-\w]+)/comments/$', comments_views.CommentList.as_view()), 

The related view looks like to:

class CommentList(generics.ListAPIView):         serializer_class = CommentSerializer     permission_classes = (permissions.IsAuthenticatedOrReadOnly,)     lookup_field = "uid"      def get_queryset(self):         comments = Comment.objects.filter(article= ???)         return comments 

For information, the related serializer

class CommentSerializer(serializers.ModelSerializer):     owner = UserSerializer()      class Meta:         model = Comment         fields = ('id', 'content', 'owner', 'created_at') 

As you can see, I've updated my get_queryset to filter comments on the article but I don't know how to catch the "uid" parameter. With an url ending with ?uid=value, i can use self.request.QUERY_PARAMS.get('uid') but in my case, I don't know how to do it. Any idea?

like image 306
billyJoe Avatar asked Jan 22 '14 19:01

billyJoe


People also ask

What is Query_params in Django?

query_params is a more correctly named synonym for request. GET . For clarity inside your code, we recommend using request. query_params instead of the Django's standard request.

How do I filter Queryset in Django Rest Framework?

The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the . get_queryset() method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways.

What is Queryset in Django Rest Framework?

queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True .

What is Lookup_url_kwarg?

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 .


1 Answers

The url parameter is stored in self.kwargs. lookup_field is the field (defaults to pk) the generic view uses inside the ORM when looking up individual model instances, lookup_url_kwarg is probably the property you want.

So try the following:

class CommentList(generics.ListAPIView):         serializer_class = CommentSerializer     permission_classes = (permissions.IsAuthenticatedOrReadOnly,)     lookup_url_kwarg = "uid"      def get_queryset(self):         uid = self.kwargs.get(self.lookup_url_kwarg)         comments = Comment.objects.filter(article=uid)         return comments 
like image 119
Scott Woodall Avatar answered Sep 22 '22 07:09

Scott Woodall