Skip to content

Commit

Permalink
Don't freeze the current query state when calling .order_by()
Browse files Browse the repository at this point in the history
This changes order_by() to eliminate its reference to
self._cursor. This meant that any parameters built by QuerySet
that followed an order_by() clause were ignored.
  • Loading branch information
Peter Teichman committed Nov 27, 2012
1 parent 9cc6164 commit 9d52e18
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 4 additions & 2 deletions mongoengine/queryset.py
Expand Up @@ -586,11 +586,13 @@ def _cursor(self):
if self._where_clause:
self._cursor_obj.where(self._where_clause)

# apply default ordering
if self._ordering:
# Apply query ordering
self._cursor_obj.sort(self._ordering)
elif self._document._meta['ordering']:
# Otherwise, apply the ordering from the document model
self.order_by(*self._document._meta['ordering'])
self._cursor_obj.sort(self._ordering)

if self._limit is not None:
self._cursor_obj.limit(self._limit - (self._skip or 0))
Expand Down Expand Up @@ -1274,7 +1276,7 @@ def order_by(self, *keys):
key_list.append((key, direction))

self._ordering = key_list
self._cursor.sort(key_list)

return self

def explain(self, format=False):
Expand Down
16 changes: 16 additions & 0 deletions tests/test_queryset.py
Expand Up @@ -1793,6 +1793,22 @@ def test_order_by(self):
ages = [p.age for p in self.Person.objects.order_by('-name')]
self.assertEqual(ages, [30, 40, 20])

def test_order_by_chaining(self):
"""Ensure that an order_by query chains properly and allows .only()
"""
self.Person(name="User A", age=20).save()
self.Person(name="User B", age=40).save()
self.Person(name="User C", age=30).save()

only_age = self.Person.objects.order_by('-age').only('age')

names = [p.name for p in only_age]
ages = [p.age for p in only_age]

# The .only('age') clause should mean that all names are None
self.assertEqual(names, [None, None, None])
self.assertEqual(ages, [40, 30, 20])

def test_confirm_order_by_reference_wont_work(self):
"""Ordering by reference is not possible. Use map / reduce.. or
denormalise"""
Expand Down

0 comments on commit 9d52e18

Please sign in to comment.