get_queryset() isn't documented as taking any args at all, let alone the kwargs of the request. You sometimes see people do "def get_queryset(self, **kwargs)" to future-proof themselves in case get_queryset does, one day, accept args. But it doesn't right now.
To get the kwargs for the request look at self.kwargs. Also, you might want to save yourself some headache later by using the provided `model = Item`, then calling super().get_queryset(), and modifying that queryset and returning the value. It makes it easier to use other mixins later or provided class-based view attributes.
class UsersItemsView(ListView):
template_name = 'testapp/user_item_list.html'
template_name = 'testapp/user_item_list.html'
model = Item
def get_queryset(self):
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(user__id=self.kwargs['userlist'])
return qs.filter(user__id=self.kwargs['userlist'])
On Sun, Jul 5, 2020 at 9:15 PM Clive Bruton <clive@indx.co.uk> wrote:
I am struggling with getting kwarg values into a queryset filter:
class UsersItemsView(ListView):
template_name = 'testapp/user_item_list.html'
def get_queryset(self, **kwargs):
print('kwargs-userlist')
print(kwargs)
#return Item.objects.filter(user__username='clive')
#return Item.objects.filter(user__id=2)
return Item.objects.filter(user__id=kwargs['userlist'])
def dispatch(self, *args, **kwargs):
print('kwargs-userlist')
print(kwargs['userlist'])
return super(UsersItemsView, self).dispatch(*args, **kwargs)
On dispatch, I can see the value for "kwargs['userlist']" printed in
the terminal.
But, the queryset returns an error:
Exception Type: KeyError
Exception Value: 'userlist'
I understand this to mean that the key 'userlist' is not in kwargs,
and this is confirmed if I "print(kwargs)" inside the get_queryset
If I use the hard-coded filters, commented-out above
("user__username='clive'", "user__id=2"), I get the result (from the
template) that I expect.
So, how do I get the "kwargs['userlist']" passed to the queryset?
Thanks
-- Clive
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5BD32BE1-331F-4AE5-BB8A-2E769D728972%40indx.co.uk.
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAD4ANxWJmZFXqt1%2ByCvGvhV5C_u7ikSghTWVwbmNv9eqWxb%3D4A%40mail.gmail.com.
No comments:
Post a Comment