Added sort method to QuerySet

This commit is contained in:
Harry Marr 2009-12-18 18:41:44 +00:00
parent 44fc9096a4
commit 5e6a6aa886
3 changed files with 37 additions and 1 deletions

View File

@ -25,7 +25,8 @@ class Document(BaseDocument):
"""Delete the document from the database. This will only take effect """Delete the document from the database. This will only take effect
if the document has been previously saved. if the document has been previously saved.
""" """
self.objects._collection.remove(self.id) object_id = self._fields['id'].to_mongo(self.id)
self.__class__.objects(_id=object_id).delete()
@classmethod @classmethod
def drop_collection(cls): def drop_collection(cls):

View File

@ -97,6 +97,22 @@ class QuerySet(object):
""" """
self._collection.remove(self._query) self._collection.remove(self._query)
def sort(self, *keys):
"""Sort the QuerySet by the keys. The order may be specified by
prepending each of the keys by a + or a -. Ascending order is assumed.
"""
key_list = []
for key in keys:
direction = pymongo.ASCENDING
if key[0] == '-':
direction = pymongo.DESCENDING
if key[0] in ('-', '+'):
key = key[1:]
key_list.append((key, direction))
self._cursor.sort(key_list)
return self
def __iter__(self): def __iter__(self):
return self return self

View File

@ -137,6 +137,25 @@ class QuerySetTest(unittest.TestCase):
self.Person.objects.delete() self.Person.objects.delete()
self.assertEqual(self.Person.objects.count(), 0) self.assertEqual(self.Person.objects.count(), 0)
def test_sort(self):
"""Ensure that QuerySets may be sorted.
"""
self.Person(name="User A", age=20).save()
self.Person(name="User B", age=40).save()
self.Person(name="User C", age=30).save()
names = [p.name for p in self.Person.objects.sort('-age')]
self.assertEqual(names, ['User B', 'User C', 'User A'])
names = [p.name for p in self.Person.objects.sort('+age')]
self.assertEqual(names, ['User A', 'User C', 'User B'])
names = [p.name for p in self.Person.objects.sort('age')]
self.assertEqual(names, ['User A', 'User C', 'User B'])
ages = [p.age for p in self.Person.objects.sort('-name')]
self.assertEqual(ages, [30, 40, 20])
def tearDown(self): def tearDown(self):
self.Person.drop_collection() self.Person.drop_collection()