1#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5from django import template
6
7register = template.Library()
8
9def objects_to_dictionaries(iterable, fields):
10    """
11    Convert an iterable into a list of dictionaries; fields should be set
12    to a comma-separated string of properties for each item included in the
13    resulting list; e.g. for a queryset:
14
15        {{ queryset | objects_to_dictionaries:"id,name" }}
16
17    will return a list like
18
19        [{'id': 1, 'name': 'foo'}, ...]
20
21    providing queryset has id and name fields
22
23    This is mostly to support serialising querysets or lists of model objects
24    to JSON
25    """
26    objects = []
27
28    if fields:
29        fields_list = [field.strip() for field in fields.split(',')]
30        for item in iterable:
31            out = {}
32            for field in fields_list:
33                out[field] = getattr(item, field)
34            objects.append(out)
35
36    return objects
37
38register.filter('objects_to_dictionaries', objects_to_dictionaries)
39