Login

Tag "dynamic-lookup"

Snippet List

Lazily lookup dynamically for templates

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 %}

  • template
  • dynamic
  • lookup
  • lazy
  • dynamic-lookup
Read More

1 snippet posted so far.