Commit b914991b authored by Baptiste Mispelon's avatar Baptiste Mispelon
Browse files

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.
parent c349bcbd
Loading
Loading
Loading
Loading
+21 −0
Original line number Diff line number Diff line
@@ -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
+14 −0
Original line number Diff line number Diff line
@@ -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'},