Opened 8 years ago

Closed 5 years ago

#10139 closed Bug (fixed)

Slicing an EmptyQuerySet gives a list, not another EmptyQuerySet

Reported by: Forest Bond Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords:
Cc: Ori Livneh Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

This causes problems if you want to do, for example, qs[0:1].get(), which is, arguably, poor form. Still, I think this is a bug.

In [25]: type(models.TestRun.objects.none()[0:10])
Out[25]: <type 'list'>

In [26]: type(models.TestRun.objects.all()[0:10])
Out[26]: <class 'django.db.models.query.QuerySet'>

Attachments (1)

queryset_slice_return_type.diff (1.0 KB) - added by Ori Livneh 5 years ago.
document which type will be returned when slicing a QuerySet

Download all attachments as: .zip

Change History (10)

comment:1 Changed 8 years ago by Malcolm Tredinnick

This isn't quite as clear as it looks. Slicing a normal QuerySet will sometimes return a list as well; it depends upon whether the results have already been retrieved from the database or not.

Probably the solution here is a documentation one, but it's worth thinking about what else might be possible. Always returning a QuerySet, though, is, from memory, a little fiddly to organise efficiently and always correctly.

comment:2 Changed 8 years ago by Jacob

Triage Stage: UnreviewedDesign decision needed

comment:3 Changed 8 years ago by Thejaswi Puthraya

Component: UncategorizedDatabase layer (models, ORM)

comment:4 Changed 6 years ago by Chris Beaven

Severity: Normal
Type: Bug

Changed 5 years ago by Ori Livneh

document which type will be returned when slicing a QuerySet

comment:5 Changed 5 years ago by Ori Livneh

Cc: Ori Livneh added
Easy pickings: unset
Has patch: set
UI/UX: unset
Version: 1.0-beta-1SVN

EmptyQuerySet is a red herring -- the list is being returned by __getitem__ on the superclass, which is QuerySet. The real problem is that the documentation for QuerySet doesn't currently do a good job explaining what type object slicing a QuerySet returns. I've added a patch to improve the documentation on this topic.

comment:6 Changed 5 years ago by Aymeric Augustin

Triage Stage: Design decision neededReady for checkin

comment:7 Changed 5 years ago by Claude Paroz

Don't forget to fix the double 'a' before the commit (Slicing a a QuerySet).

comment:8 Changed 5 years ago by Aymeric Augustin

In fact there's no such thing as an unevaluated EmptyQuerySet: __init__ sets self._result_cache = [].

comment:9 Changed 5 years ago by Aymeric Augustin

Resolution: fixed
Status: newclosed

In [17383]:

Fixed #10139 -- Clarified that slicing an evaluated QuerySet returns a list, not a QuerySet. Thanks ori for the patch.

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