Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django dot-lookup syntax to access variable attributes

Tags:

django

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

The template system uses dot-lookup syntax to access variable attributes. In the example of {{ question.question_text }}, first Django does a dictionary lookup on the object question. Failing that, it tries an attribute lookup – which works, in this case. If attribute lookup had failed, it would’ve tried a list-index lookup.

What is the difference between dictionary, attribute, and list-index lookup?

like image 327
css3newbie Avatar asked Dec 24 '22 14:12

css3newbie


2 Answers

Dot lookup in Django templates:

When the Django template system encounters a dot in a variable name {{foo.bar}}, it tries the lookups, in the below order:

The template system uses the first lookup type that works. It’s short-circuit logic.

1. Dictionary lookup

In dictionary lookup, it will try to perform lookup assuming foo as a dictionary and bar as a key in that dictionary.

foo["bar"] # perform dictionary lookup   

2. Attribute lookup.

When the dictionary lookup fails, it performs attribute lookup i.e try to access bar attribute in foo.

foo.bar # perform attribute lookup   

3. List-index lookup.

When the attribute lookup fails, it will try to perform list-index lookup i.e try to access bar index in foo.

foo[bar] # perform index lookup   

Example from official docs:

>>> from django.template import Context, Template
>>> t = Template("My name is {{ person.first_name }}.")

# Dictionary lookup
>>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
>>> t.render(Context(d))
"My name is Joe."

# Attribute lookup
>>> class PersonClass: pass
>>> p = PersonClass()
>>> p.first_name = "Ron"
>>> p.last_name = "Nasty"
>>> t.render(Context({"person": p}))
"My name is Ron."

# List-Index lookup
>>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
>>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
>>> t.render(c)
"The first stooge in the list is Larry."
like image 159
Rahul Gupta Avatar answered Feb 15 '23 07:02

Rahul Gupta


From the Django documentation:

Dictionary lookup. Example: foo["bar"]
Attribute lookup. Example: foo.bar
List-index lookup. Example: foo[bar]
like image 32
Emil Stenström Avatar answered Feb 15 '23 06:02

Emil Stenström