summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBaptiste Mispelon <bmispelon@gmail.com>2013-11-06 00:17:28 +0100
committerBaptiste Mispelon <bmispelon@gmail.com>2013-11-06 00:26:58 +0100
commitb914991b3705cb6c91013d962c55cda9deb18d83 (patch)
tree702b997c0951bc36dafbf89ecd8c94679fce1427
parentc349bcbdf9c3520a0050bddf49ea59d9418c3ecb (diff)
Added more tests and documentation for dictsort.
It's possible to use something like {{ foo|dictsort:'bar.baz' }} but this wasn't tested or documented.
-rw-r--r--docs/ref/templates/builtins.txt21
-rw-r--r--tests/defaultfilters/tests.py14
2 files changed, 35 insertions, 0 deletions
diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
index 48412239ad..d8f76dc680 100644
--- a/docs/ref/templates/builtins.txt
+++ b/docs/ref/templates/builtins.txt
@@ -1433,6 +1433,27 @@ then the output would be:
{'name': 'zed', 'age': 19},
]
+You can also do more complicated things like::
+ {{ for book in books|dictsort:"author.age"
+ * {{ book.title }} ({{ book.author.name }})
+ {% endfor %}
+
+If ``books`` is:
+
+.. code-block:: python
+
+ [
+ {'title': '1984', 'author': {'name': 'George', 'age': 45}},
+ {'title': 'Timequake', 'author': {'name': 'Kurt', 'age': 75}},
+ {'title': 'Alice', 'author': {'name': 'Lewis', 'age': 33}},
+ ]
+
+the the output would be::
+
+ * Alice (Lewis)
+ * 1984 (George)
+ * Timequake (Kurt)
+
.. templatefilter:: dictsortreversed
dictsortreversed
diff --git a/tests/defaultfilters/tests.py b/tests/defaultfilters/tests.py
index 52a61a1ac7..92972e1edb 100644
--- a/tests/defaultfilters/tests.py
+++ b/tests/defaultfilters/tests.py
@@ -441,6 +441,20 @@ class DefaultFiltersTests(TestCase):
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '')
+ def test_dictsort_complex_sorting_key(self):
+ """
+ Since dictsort uses template.Variable under the hood, it can sort
+ on keys like 'foo.bar'.
+ """
+ data = [
+ {'foo': {'bar': 1, 'baz': 'c'}},
+ {'foo': {'bar': 2, 'baz': 'b'}},
+ {'foo': {'bar': 3, 'baz': 'a'}},
+ ]
+ sorted_data = dictsort(data, 'foo.baz')
+
+ self.assertEqual([d['foo']['bar'] for d in sorted_data], [3, 2, 1])
+
def test_dictsortreversed(self):
sorted_dicts = dictsortreversed([{'age': 23, 'name': 'Barbara-Ann'},
{'age': 63, 'name': 'Ra Ra Rasputin'},