From 0c8ac0972c9b1a5af95d40334b83cf5f31d56331 Mon Sep 17 00:00:00 2001 From: Luke Plant Date: Fri, 26 May 2006 18:41:03 +0000 Subject: [PATCH] Made negative indexing on QuerySet instances raise an assertion error (previously it just returned incorrect results). git-svn-id: http://code.djangoproject.com/svn/django/trunk@2992 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/query.py | 3 +++ tests/modeltests/basic/models.py | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/django/db/models/query.py b/django/db/models/query.py index 61032602fa..1107269235 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -95,6 +95,9 @@ class QuerySet(object): def __getitem__(self, k): "Retrieve an item or slice from the set of results." + assert (not isinstance(k, slice) and (k >= 0)) \ + or (isinstance(k, slice) and (k.start is None or k.start >= 0) and (k.stop is None or k.stop >= 0)), \ + "Negative indexing is not supported." if self._result_cache is None: if isinstance(k, slice): # Offset: diff --git a/tests/modeltests/basic/models.py b/tests/modeltests/basic/models.py index 0470d6bc9b..f60c3777e7 100644 --- a/tests/modeltests/basic/models.py +++ b/tests/modeltests/basic/models.py @@ -283,6 +283,16 @@ Traceback (most recent call last): ... AssertionError: Cannot combine queries once a slice has been taken. +# Negative slices are not supported, due to database constraints. +# (hint: inverting your ordering might do what you need). +>>> Article.objects.all()[-1] +Traceback (most recent call last): + ... +AssertionError: Negative indexing is not supported. +>>> Article.objects.all()[0:-5] +Traceback (most recent call last): + ... +AssertionError: Negative indexing is not supported. # An Article instance doesn't have access to the "objects" attribute. # That's only available on the class.