Opened 7 years ago

Closed 7 years ago

#6899 closed (fixed)

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

Reported by: brodie 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: UI/UX:

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 7 years ago.
Fixes _QuerySet.nonzero for empty query sets (with test case)
nonzero-queryset-2.diff (1.3 KB) - added by cide@… 7 years ago.
Fixes _QuerySet.nonzero for empty query sets (with test case). Works with ValuesQuerySets.

Download all attachments as: .zip

Change History (7)

Changed 7 years ago by brodie

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

comment:1 Changed 7 years ago by anonymous

  • Keywords qs-rf added; qs-ref removed
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 7 years ago by Alex

  • Triage Stage changed from Unreviewed to Accepted

comment:3 Changed 7 years ago by cide@…

  • 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.

Changed 7 years ago by cide@…

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

comment:4 Changed 7 years ago by cide@…

  • 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 Changed 7 years ago by mtredinnick

  • Resolution set to fixed
  • Status changed from new to closed

(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