URL parameters in Django get_queryset() function

huLimb0w report abuse

I am developing a Django application. For one of my class-based views, I want to use "generic.ListView" as a base class. This class assumes I will override "get_queryset()" method, which should prepare data for rendering in the HTML template. But to fetch this data from the database, I need to use the parameters taken from URL (GET parameters). In the same time, this method doesn't allow to pass parameters to it (only "self" object). How can I pass the needed parameter to this method?


maria_maria report abuse __ edited

Can you show an example of your code, please? Namely, I am interested in the path in urls.py file.

huLimb0w report abuse __ edited

Here is the path:

path('users/<int:pk>/activity/', views.UserActivityView.as_view(), name='user_activity')

The "pk" parameter is what I need to pass to the "get_queryset()" method:

def get_queryset(self, pk):
    author = do_something_to_find_author(pk)
    return Post.objects.filter(author=author).order_by("-creation_date")

However, this throws an error. When I try to use "self.request.pk" - this doesn't work as well.

maria_maria report abuse

Actually, get_queryset() doesn't take additional parameters as input. But you can use self.kwargs object to access URL parameters. Something like this: pk = self.kwargs['pk']

huLimb0w report abuse

Great, this works! Thank you very much!

Add Answer

Need support?

Just drop us an email to ... Show more