From b914991b3705cb6c91013d962c55cda9deb18d83 Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Wed, 6 Nov 2013 00:17:28 +0100 Subject: [PATCH] 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. --- docs/ref/templates/builtins.txt | 21 +++++++++++++++++++++ tests/defaultfilters/tests.py | 14 ++++++++++++++ 2 files changed, 35 insertions(+) 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'},