Fixed bug with Meta.ordering being ignored when slicing a single item off a QuerySet. Thanks, Gábor Fawkes.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@2970 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Luke Plant 2006-05-23 19:55:30 +00:00
parent 23269289be
commit a666b98783
3 changed files with 8 additions and 3 deletions

View File

@ -269,8 +269,8 @@ class Model(object):
q._params.extend([param, param, getattr(self, self._meta.pk.attname)]) q._params.extend([param, param, getattr(self, self._meta.pk.attname)])
try: try:
return q[0] return q[0]
except IndexError, e: except IndexError:
raise self.DoesNotExist, e.args raise self.DoesNotExist, "%s matching query does not exist." % self.__class__._meta.object_name
def _get_next_or_previous_in_order(self, is_next): def _get_next_or_previous_in_order(self, is_next):
cachename = "__%s_order_cache" % is_next cachename = "__%s_order_cache" % is_next

View File

@ -129,7 +129,7 @@ class QuerySet(object):
return list(self._clone(_offset=offset, _limit=limit))[::k.step] return list(self._clone(_offset=offset, _limit=limit))[::k.step]
else: else:
try: try:
return self._clone(_offset=k, _limit=1).get() return list(self._clone(_offset=k, _limit=1))[0]
except self.model.DoesNotExist, e: except self.model.DoesNotExist, e:
raise IndexError, e.args raise IndexError, e.args
else: else:
@ -193,6 +193,7 @@ class QuerySet(object):
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
"Performs the SELECT and returns a single object matching the given keyword arguments." "Performs the SELECT and returns a single object matching the given keyword arguments."
clone = self.filter(*args, **kwargs) clone = self.filter(*args, **kwargs)
# clean up SQL by removing unneeded ORDER BY
if not clone._order_by: if not clone._order_by:
clone._order_by = () clone._order_by = ()
obj_list = list(clone) obj_list = list(clone)

View File

@ -56,6 +56,10 @@ API_TESTS = """
>>> Article.objects.order_by('headline')[1:3] >>> Article.objects.order_by('headline')[1:3]
[Article 2, Article 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 # Use '?' to order randomly. (We're using [...] in the output to indicate we
# don't know what order the output will be in. # don't know what order the output will be in.
>>> Article.objects.order_by('?') >>> Article.objects.order_by('?')