Login

Lazily lookup dynamically for templates

Author:
axiak
Posted:
March 8, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

If you've ever wanted to dynamically lookup values in the template layer (e.g. dictionary[bar]), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data.

These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example:

from lazy_lookup import lazy_lookup_dict

def some_view(request):
   users = User.objects.values('id', 'username')
   articles = Article.objects.values('user', 'title', 'body')
   articles = dict([(x['user'], x) for x in articles])
   return render_to_response('some_template.html',
                           {'data': lazy_lookup_dict(users, key=lambda x: x['id'],
                                                     article=articles,
                                                     item_name='user')})

Then in the template layer you'd write something like:

{% for user_data in data %}
  {{ user_data.user.username }}, {{ user_data.article.title }}
{% endfor %}
 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def lazy_lookup_tuple(iterable, *args, **kwargs):
    """ Generates a lookup over all iterations of the iterable.
    The keyword parameters are:
      - key: A function which, given an item in the iterable,
             returns the key upon which to lookup from the lookup
             objects.
             Defaults to the identity function.
      - default: The value which a field defaults to if nothing
                 the item doesn't coorespond in the lookup.
                 Defaults to None.
    All position arguments (excepting the first one) are objects
    that support lookup via __getitem__ (e.g. a dict object).

    This returns a generator which yields tuples of 
    the form:
       (item, args[0][key(item)], args[1][key(item)], ...)

    """
    default = None
    key_func = lambda x: x

    if 'key' in kwargs:
        key_func = kwargs['key']
    if 'default' in kwargs:
        default = kwargs['default']

    def get_item(object, key):
        try:
            return object[key]
        except KeyError:
            if callable(default):
                return default(key)
            else:
                return default

    for item in iterable:
        key = key_func(item)
        yield tuple([item] + map(lambda arg: get_item(arg, key), args))


def lazy_lookup_dict(iterable, *args, **kwargs):
    """ Generates a lookup over all iterations of the iterable.
    The keyword parameters are:
      - key: A function which, given an item in the iterable,
             returns the key upon which to lookup from the lookup
             objects.
             Defaults to the identity function.
      - default: The value which a field defaults to if nothing
                 the item doesn't coorespond in the lookup.
                 Defaults to None.
      - item_name: The label for the item in the dictionary that's
                   yielded.
                   Defaults to 'item'.
    All keyword arguments (except the above ones) are objects
    that support lookup via __getitem__ (e.g. a dict object).

    This returns a generator which yields dictionaries of 
    the form:
       {'item': item, kwarg_name1: kwarg_value1[key(item)], ...}

    """
    default = None
    key_func = lambda x: x
    item_name = 'item'

    if 'key' in kwargs:
        key_func = kwargs['key']
        del kwargs['key']
    if 'default' in kwargs:
        default = kwargs['default']
        del kwargs['default']
    if 'item_name' in kwargs:
        item_name = kwargs['item_name']
        del kwargs['item_name']

    def get_item(object, key):
        try:
            return object[key]
        except KeyError:
            if callable(default):
                return default(key)
            else:
                return default

    for item in iterable:
        key = key_func(item)
        yield dict([(item_name, item)] + 
                   map(lambda kwarg: (kwarg[0], get_item(kwarg[1], key)), kwargs.items()))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.