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