Opened 17 years ago

Closed 17 years ago

#4399 closed (duplicate)

Add __nonzero__ to allow querysets to efficiently test for emptiness

Reported by: Michael Axiak <axiak@…> 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)

5358_added_nonzero_for_queryset.diff (593 bytes ) - added by Michael Axiak <axiak@…> 17 years ago.
Simple patch to add __nonzero__ to queryset

Download all attachments as: .zip

Change History (2)

by Michael Axiak <axiak@…>, 17 years ago

Simple patch to add __nonzero__ to queryset

comment:1 by Malcolm Tredinnick, 17 years ago

Resolution: duplicate
Status: newclosed

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.

Note: See TracTickets for help on using tickets.
Back to Top