I have a method visible
on a QuerySet
class which should return all articles an user can see. If the user is not logged in, all articles with min_age
should'nt be visible, otherwise, if the user is logged in, all articles which min_age
is lower than the user's age should be visible. I wrote this code but I think it can be improved. These raise AttributeError
aren't good practice, I know, but how can I improve it?
def visible(self, request=None):
articles = self.filter(hidden=False)
try:
if request is not None:
if request.user.is_authenticated:
if request.user.userprofile.has_filled_out:
articles = articles.filter(min_age__lte=request.user.userprofile.age)
else:
raise AttributeError
else:
raise AttributeError
else:
raise AttributeError
except AttributeError:
articles = articles.filter(min_age=None)
return articles
1 Answer 1
Just put all those conditions into single IF using AND/OR. return limited queryset in ELSE branch.
-
\$\begingroup\$ Omg I am so dumb. I don't know why I didn't think that way! Thank you very much! \$\endgroup\$Myzel394– Myzel3942019年12月22日 11:21:28 +00:00Commented Dec 22, 2019 at 11:21
-
1\$\begingroup\$ Thats how we learn, cheers ;) \$\endgroup\$K.H.– K.H.2019年12月22日 11:22:19 +00:00Commented Dec 22, 2019 at 11:22