Code

Opened 7 years ago

Closed 7 years ago

#4399 closed (duplicate)

Add __nonzero__ to allow querysets to efficiently test for emptiness

Reported by: Michael Axiak <axiak@…> Owned by: adrian
Component: Database layer (models, ORM) Version: master
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: UI/UX:

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@…> 7 years ago.
Simple patch to add __nonzero__ to queryset

Download all attachments as: .zip

Change History (2)

Changed 7 years ago by Michael Axiak <axiak@…>

Simple patch to add __nonzero__ to queryset

comment:1 Changed 7 years ago by mtredinnick

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to 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.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.