From a666b987835e99c55f51cd2feaf287111cbfcd86 Mon Sep 17 00:00:00 2001 From: Luke Plant Date: Tue, 23 May 2006 19:55:30 +0000 Subject: [PATCH] =?UTF-8?q?Fixed=20bug=20with=20Meta.ordering=20being=20ig?= =?UTF-8?q?nored=20when=20slicing=20a=20single=20item=20off=20a=20QuerySet?= =?UTF-8?q?.=20=20Thanks,=20G=C3=A1bor=20Fawkes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git-svn-id: http://code.djangoproject.com/svn/django/trunk@2970 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/base.py | 4 ++-- django/db/models/query.py | 3 ++- tests/modeltests/ordering/models.py | 4 ++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/django/db/models/base.py b/django/db/models/base.py index 08a81c9ab9d..bc722de505d 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -269,8 +269,8 @@ class Model(object): q._params.extend([param, param, getattr(self, self._meta.pk.attname)]) try: return q[0] - except IndexError, e: - raise self.DoesNotExist, e.args + except IndexError: + raise self.DoesNotExist, "%s matching query does not exist." % self.__class__._meta.object_name def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next diff --git a/django/db/models/query.py b/django/db/models/query.py index b8fc0c695f2..61032602fa7 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -129,7 +129,7 @@ class QuerySet(object): return list(self._clone(_offset=offset, _limit=limit))[::k.step] else: try: - return self._clone(_offset=k, _limit=1).get() + return list(self._clone(_offset=k, _limit=1))[0] except self.model.DoesNotExist, e: raise IndexError, e.args else: @@ -193,6 +193,7 @@ class QuerySet(object): def get(self, *args, **kwargs): "Performs the SELECT and returns a single object matching the given keyword arguments." clone = self.filter(*args, **kwargs) + # clean up SQL by removing unneeded ORDER BY if not clone._order_by: clone._order_by = () obj_list = list(clone) diff --git a/tests/modeltests/ordering/models.py b/tests/modeltests/ordering/models.py index de08a757557..8b56731c55e 100644 --- a/tests/modeltests/ordering/models.py +++ b/tests/modeltests/ordering/models.py @@ -56,6 +56,10 @@ API_TESTS = """ >>> Article.objects.order_by('headline')[1:3] [Article 2, Article 3] +# Getting a single item should work too: +>>> Article.objects.all()[0] +Article 4 + # Use '?' to order randomly. (We're using [...] in the output to indicate we # don't know what order the output will be in. >>> Article.objects.order_by('?')