QuerySet last() and reverse() confusing when used with ordered slices
|Reported by:||jdufresne||Owned by:||merll|
|Component:||Database layer (models, ORM)||Version:||1.6|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
I ran all tests below with MySQL backend.
Given the following model:
class MyModel(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ['name'] def __unicode__(self): return self.name
From the following test script I receive the output:
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djtest.settings") from myapp.models import MyModel MyModel.objects.all().delete() for i in range(10): m = MyModel(name='model%d' % i) m.save() print MyModel.objects.all()[0:5] print MyModel.objects.all()[0:5].last() print MyModel.objects.all()[0:5].reverse()
[<MyModel: model0>, <MyModel: model1>, <MyModel: model2>, <MyModel: model3>, <MyModel: model4>] model9 [<MyModel: model9>, <MyModel: model8>, <MyModel: model7>, <MyModel: model6>, <MyModel: model5>, <MyModel: model4>, <MyModel: model3>, <MyModel: model2>, <MyModel: model1>, <MyModel: model0>]
In my opinion, the lines that show the output of last() and reverse() are confusing. My naive expectation was that each of these would be operating on the slice. That is, the last value from the slice or the reverse order of the slice.
model4 [<MyModel: model4>, <MyModel: model3>, ...
Of course, after thinking about how this might get translated to SQL I understand why this happens. Making this a leaky abstraction. In my opinion, if expected behavior can't be realized an exception preventing the operation makes more sense.
The original reason I bumped into this is I was creating a custom Paginator to create page labels based on the first and last item on the page. As Paginator uses slices, calling last() produced unexpected (to me) results.
Change History (4)
comment:1 Changed 15 months ago by merll
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
comment:2 Changed 15 months ago by merll
- Owner changed from nobody to merll
- Status changed from new to assigned