Opened 17 years ago
Closed 17 years ago
#4399 closed (duplicate)
Add __nonzero__ to allow querysets to efficiently test for emptiness
Reported by: | Owned by: | Adrian Holovaty | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Keywords: | database, performance, existence, patch | |
Cc: | axiak@… | Triage Stage: | Unreviewed |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
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)
Attachments (1)
Change History (2)
by , 17 years ago
Attachment: | 5358_added_nonzero_for_queryset.diff added |
---|
comment:1 by , 17 years ago
Resolution: | → duplicate |
---|---|
Status: | new → closed |
Dupe of #2430.
Coincidentally, I started working on this problem (and a couple of other len()-related problems) last night and I've got a fix that doesn't require the extra query, using the technique at the end of that ticket.
So, thanks for the patch, but we can fix it in a way that incurs zero extra queries. Should have something in later today or tomorrow, depending on how much the universe hates me.
Simple patch to add
__nonzero__
to queryset