pylint-django icon indicating copy to clipboard operation
pylint-django copied to clipboard

Add check to warn against usage of querysets in boolean expressions

Open sevdog opened this issue 3 years ago • 2 comments

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.

sevdog avatar Nov 21 '22 14:11 sevdog

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.

jacobtylerwalls avatar Feb 24 '24 18:02 jacobtylerwalls

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)

braiam avatar Jun 12 '24 11:06 braiam