Django

Code

Ticket #6899 (closed: fixed)

Opened 1 year ago

Last modified 1 year ago

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

Reported by: brodie Assigned to: nobody
Milestone: Component: Database layer (models, ORM)
Version: queryset-refactor Keywords: qs-rf
Cc: Triage Stage: Accepted
Has patch: 1 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

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

nonzero-queryset.diff (1.1 kB) - added by brodie on 03/26/08 18:03:04.
Fixes _QuerySet.nonzero for empty query sets (with test case)
nonzero-queryset-2.diff (1.3 kB) - added by cide@ctmod.net on 03/26/08 22:23:32.
Fixes _QuerySet.nonzero for empty query sets (with test case). Works with ValuesQuerySets?.

Change History

03/26/08 18:03:04 changed by brodie

  • attachment nonzero-queryset.diff added.

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

03/26/08 18:05:00 changed by anonymous

  • keywords changed from qs-ref to qs-rf.
  • needs_better_patch changed.
  • needs_tests changed.
  • needs_docs changed.

03/26/08 18:06:37 changed by Alex

  • stage changed from Unreviewed to Accepted.

03/26/08 21:32:43 changed by cide@ctmod.net

  • needs_better_patch set to 1.

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.

03/26/08 22:23:32 changed by cide@ctmod.net

  • attachment nonzero-queryset-2.diff added.

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

03/26/08 22:26:53 changed by cide@ctmod.net

  • needs_better_patch deleted.

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

04/12/08 22:22:39 changed by mtredinnick

  • status changed from new to closed.
  • resolution set to fixed.

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


Add/Change #6899 (_QuerySet.__nonzero__ returns True for empty query sets with cached results)




Change Properties
Action