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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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