1
\$\begingroup\$

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
asked Dec 21, 2019 at 22:24
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Just put all those conditions into single IF using AND/OR. return limited queryset in ELSE branch.

answered Dec 22, 2019 at 10:35
\$\endgroup\$
2
  • \$\begingroup\$ Omg I am so dumb. I don't know why I didn't think that way! Thank you very much! \$\endgroup\$ Commented Dec 22, 2019 at 11:21
  • 1
    \$\begingroup\$ Thats how we learn, cheers ;) \$\endgroup\$ Commented Dec 22, 2019 at 11:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.