Add __nonzero__ to allow querysets to efficiently test for emptiness
|Reported by:||Owned by:||Adrian Holovaty|
|Component:||Database layer (models, ORM)||Version:||master|
|Severity:||Keywords:||database, performance, existence, patch|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Currently, if you do:
if Model.objects.filter(Complicated): ...
you're asking for performance trouble, since it will issue a
__len__ statement on it. Most people will solve this problem by doing:
if Model.objects.filter(Complicated).count() > 0: ...
But this is still much slower than doing a SELECT LIMIT 1. Thus, I propose adding a
__nonzero__ function, so that the first method of checking for emptiness does the right thing. (http://docs.python.org/ref/customization.html)