Skip to content

Commit

Permalink
Added support for SortBy operator to simplify the creation of sort in…
Browse files Browse the repository at this point in the history
…structions.
  • Loading branch information
anthonyjb committed Aug 28, 2017
1 parent babdac3 commit 045dc93
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
18 changes: 18 additions & 0 deletions mongoframes/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import re

from pymongo import (ASCENDING, DESCENDING)

__all__ = [
# Queries
Expand All @@ -24,6 +25,9 @@
'Or',
'Nor',

# Sorting
'SortBy',

# Utils
'to_refs'
]
Expand Down Expand Up @@ -240,6 +244,20 @@ class Nor(Group):
operator = '$nor'


# Sorting

def SortBy(*qs):
"""Convert a list of Q objects into list of sort instructions"""

sort = []
for q in qs:
if q._path.endswith('.desc'):
sort.append((q._path[:-5], DESCENDING))
else:
sort.append((q._path, ASCENDING))
return sort


# Utils

def deep_merge(source, dest):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
# https://packaging.python.org/en/latest/requirements.html
install_requires=[
'blinker>=1.4',
'Faker>=0.7.7',
'Faker>=0.7.18',
'pymongo>=3'
],

Expand Down
6 changes: 6 additions & 0 deletions tests/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ def test_nor():
assert Nor(Q.foo == 123, Q.bar != 456).to_dict() == \
{'$nor': [{'foo': 123}, {'bar': {'$ne': 456}}]}

# Sorting

def test_sort_by():
"""Should return sort instructions for a list of `Q` instances"""
assert SortBy(Q.dob.desc, Q.name) == [('dob', -1), ('name', 1)]


# Utils

Expand Down

0 comments on commit 045dc93

Please sign in to comment.