#30957: Inconsistent slice behaviour on cached vs non-cached result lists in
QuerySets
-------------------------------------------+------------------------
Reporter: Karolis Ryselis | Owner: nobody
Type: Uncategorized | Status: new
Component: Uncategorized | Version: 2.2
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------------+------------------------
consider a model
{{{
class Good(models.Model):
title = models.CharField(max_length=16)
}}}
Suppose we have created some objects of this model in database.
Getting a slice of existing queryset returns a new queryset:
{{{
g = Good.objects.all()
print(type(g[0:1]))
}}}
outputs
{{{
<class 'django.db.models.query.QuerySet'>
}}}
however, getting a slice on an evaluated queryset returns a list, not
queryset:
{{{
g = Good.objects.all()
list(g) # force evaluation
print(type(g[0:1]))
}}}
outputs
{{{
<class 'list'>
}}}
This happens because {{{__getitem__}}} in {{{QuerySet}}} uses result cache
if it's available, and result cache is always saved as list. Excerpt from
{{{QuerySet,__getitem__}}}:
{{{
if self._result_cache is not None:
return self._result_cache[k]
}}}
Excerpt from {{{QuerySet._fetch_all}}}:
{{{
if self._result_cache is None:
self._result_cache = list(self._iterable_class(self))
}}}
If {{{_result_cache}}} is {{{None}}}, then {{{__getitem__}}} makes a query
and returns a proper QuerySet. This produces extremely hard-to-catch bugs,
because the return type depends on QuerySet evaluation state.
The error was reproduced in version 2.2.6
--
Ticket URL: <https://code.djangoproject.com/ticket/30957>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/050.f66b5e9f23a8eed80337f710e84db460%40djangoproject.com.