aboutsummaryrefslogtreecommitdiffstats
path: root/lib/srtgui/templatetags/objects_to_dictionaries_filter.py
blob: 0dcc7d2714a723ea4bb1cef8f8146e37ddf07802 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from django import template
import json

register = template.Library()

def objects_to_dictionaries(iterable, fields):
    """
    Convert an iterable into a list of dictionaries; fields should be set
    to a comma-separated string of properties for each item included in the
    resulting list; e.g. for a queryset:

        {{ queryset | objects_to_dictionaries:"id,name" }}

    will return a list like

        [{'id': 1, 'name': 'foo'}, ...]

    providing queryset has id and name fields

    This is mostly to support serialising querysets or lists of model objects
    to JSON
    """
    objects = []

    if fields:
        fields_list = [field.strip() for field in fields.split(',')]
        for item in iterable:
            out = {}
            for field in fields_list:
                out[field] = getattr(item, field)
            objects.append(out)

    return objects

register.filter('objects_to_dictionaries', objects_to_dictionaries)