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
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.