Brad Bishop | c342db3 | 2019-05-15 21:57:59 -0400 | [diff] [blame^] | 1 | # |
| 2 | # SPDX-License-Identifier: GPL-2.0-only |
| 3 | # |
| 4 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 5 | from django import template |
| 6 | import json |
| 7 | |
| 8 | register = template.Library() |
| 9 | |
| 10 | def 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 | |
| 39 | register.filter('objects_to_dictionaries', objects_to_dictionaries) |