diff options
Diffstat (limited to 'bitbake/lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py')
-rw-r--r-- | bitbake/lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/bitbake/lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py b/bitbake/lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py new file mode 100644 index 0000000000..0dcc7d2714 --- /dev/null +++ b/bitbake/lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py | |||
@@ -0,0 +1,35 @@ | |||
1 | from django import template | ||
2 | import json | ||
3 | |||
4 | register = template.Library() | ||
5 | |||
6 | def objects_to_dictionaries(iterable, fields): | ||
7 | """ | ||
8 | Convert an iterable into a list of dictionaries; fields should be set | ||
9 | to a comma-separated string of properties for each item included in the | ||
10 | resulting list; e.g. for a queryset: | ||
11 | |||
12 | {{ queryset | objects_to_dictionaries:"id,name" }} | ||
13 | |||
14 | will return a list like | ||
15 | |||
16 | [{'id': 1, 'name': 'foo'}, ...] | ||
17 | |||
18 | providing queryset has id and name fields | ||
19 | |||
20 | This is mostly to support serialising querysets or lists of model objects | ||
21 | to JSON | ||
22 | """ | ||
23 | objects = [] | ||
24 | |||
25 | if fields: | ||
26 | fields_list = [field.strip() for field in fields.split(',')] | ||
27 | for item in iterable: | ||
28 | out = {} | ||
29 | for field in fields_list: | ||
30 | out[field] = getattr(item, field) | ||
31 | objects.append(out) | ||
32 | |||
33 | return objects | ||
34 | |||
35 | register.filter('objects_to_dictionaries', objects_to_dictionaries) | ||