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.
This commit is contained in:
Baptiste Mispelon 2013-11-06 00:17:28 +01:00
parent c349bcbdf9
commit b914991b37
2 changed files with 35 additions and 0 deletions

View File

@ -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

View File

@ -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'},