Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check to warn against usage of querysets in boolean expressions #382

Open
sevdog opened this issue Nov 21, 2022 · 2 comments
Open

Add check to warn against usage of querysets in boolean expressions #382

sevdog opened this issue Nov 21, 2022 · 2 comments

Comments

@sevdog
Copy link

sevdog commented Nov 21, 2022

Django querysets can be used in a python boolean expression (ie: bool(qs) or if qs:), however in many cases this is considered a bad practice in django since the __bool__ method causes the whole queryset to be evaluated. The best practice suggests to use .exists() instead.

If possible, it would be very useful to have a check/test which warns against these usage.

@jacobtylerwalls
Copy link
Member

That's a great document. In fact, right below the passage you linked, it warns not to overuse exists(). So this check would really only be useful if it could tell with confidence that the queryset is not evaluated afterward.

@braiam
Copy link

braiam commented Jun 12, 2024

This would be a very context dependent test. If the queryset is not being passed around, it could be a useful suggestion. If the only check is for example:

pending = Transaction.objects.filter(status="pending")
if pending:
  context.update({"pending": True})

In this specific context, it would be useful. Same if we are only interested in passing the count. Now, if we are going to use the rest of the queryset, then the suggestion wouldn't help. (Note, if the queryset is 0, it won't matter which of the two are used, the issue is if there's records that match our queryset, which would mean that data is being transferred and loaded into django)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants