I’d like to write an except clause that redirects the user if there isn’t something in a queryset. Any suggestions welcome. I’m a Python noob, which I get is the issue here.
Here is my current code:
def get_queryset(self):
try:
var = Model.objects.filter(user=self.request.user, done=False)
except:
pass
return var
I want to do something like this:
def get_queryset(self):
try:
var = Model.objects.filter(user=self.request.user, done=False)
except:
redirect('add_view')
return var
A try except block in the
get_querysetmethod isn’t really appropriate. Firstly,Model.objects.filter()won’t raise an exception if the queryset is empty – it just returns an empty queryset. Secondly, theget_querysetmethod is meant to return a queryset, not anHttpResponse, so if you try to redirect inside that method, you’ll run into problems.I think you might find it easier to write a function based view. A first attempt might look like this:
The advantage is that the flow of your function is pretty straight forward. This doesn’t have as many features as the
ListViewgeneric class based view (it’s missing pagination for example), but it is pretty clear to anyone reading your code what the view is doing.If you really want to use the class based view, you have to dig into the CBV documentation for multiple object mixins and the source code, and find a suitable method to override.
In this case, you’ll find that the
ListViewbehaviour is quite different to what you want, because it never redirects. It displays an empty page by default, or a 404 page if you setallow_empty = False. I think you would have to override thegetmethod to look something like this (untested).