Count Vs Exists (ARCH2063)
Key python.orm.count-vs-exists · Severity info · Category orm
Using count() > 0 to test for presence counts all rows; exists() stops at the first row and gives the same answer far more cheaply.
Incorrect
Section titled “Incorrect”if User.objects.filter(email=email).count() > 0: raise ValueError("taken") # needless full countCorrect
Section titled “Correct”if User.objects.filter(email=email).exists(): raise ValueError("taken") # short-circuits at first rowUse the short-circuiting exists() instead of count() > 0 for presence checks.