Opened 16 years ago

Closed 16 years ago

#6899 closed (fixed)

_QuerySet.__nonzero__ returns True for empty query sets with cached results

Reported by: Brodie Rao Owned by: nobody
Component: Database layer (models, ORM) Version: queryset-refactor
Severity: Keywords: qs-rf
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given any sort of model with zero instances/rows, the following will currently occur:

>>> objects = Foo.objects.all()
>>> bool(objects)
False
>>> bool(objects)
True

_QuerySet.__nonzero__ unconditionally returns True when the result cache is populated, even if nothing is in the cache (i.e. there are no results).

I'm attaching a patch that fixes this behavior, and a test case for it.

Attachments (2)

nonzero-queryset.diff (1.1 KB ) - added by Brodie Rao 16 years ago.
Fixes _QuerySet.nonzero for empty query sets (with test case)
nonzero-queryset-2.diff (1.3 KB ) - added by cide@… 16 years ago.
Fixes _QuerySet.nonzero for empty query sets (with test case). Works with ValuesQuerySets.

Download all attachments as: .zip

Change History (7)

by Brodie Rao, 16 years ago

Attachment: nonzero-queryset.diff added

Fixes _QuerySet.nonzero for empty query sets (with test case)

comment:1 by anonymous, 16 years ago

Keywords: qs-rf added; qs-ref removed

comment:2 by Alex Gaynor, 16 years ago

Triage Stage: UnreviewedAccepted

comment:3 by cide@…, 16 years ago

Patch needs improvement: set

While this patch fixes the nonzero issue, it appears to break stuff as well. More specifically, while running this patch, django attempted to insert several already existing entries into the database for some reason (with the same primary key) - resulting in several IntegrityErrors. Removing the patch immediately fixed the issue.

by cide@…, 16 years ago

Attachment: nonzero-queryset-2.diff added

Fixes _QuerySet.nonzero for empty query sets (with test case). Works with ValuesQuerySets.

comment:4 by cide@…, 16 years ago

Patch needs improvement: unset

I have attached a patch that fixes the issues I had. The first patch relied on QuerySet._result_cache evaluating to True in a boolean context after iter(instance).next() was called. This was not the case with ValuesQuerySets. In this patch, nonzero returns True if the next() call does not raise StopIteration.

comment:5 by Malcolm Tredinnick, 16 years ago

Resolution: fixed
Status: newclosed

(In [7417]) Fixed #6899 -- Fixed a problem with boolean evaluation of empty querysets.
Based on patches from cide@… and brodie.

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