Django Templates First element of a List

Srikar Appalaraju picture Srikar Appalaraju · Nov 26, 2010 · Viewed 41.9k times · Source

I pass a dictionary to my Django Template,

Dictionary & Template is like this -

lists[listid] = {'name': l.listname, 'docs': l.userdocs.order_by('-id')}

{% for k, v in lists.items %}
    <ul><li>Count: {{ v.docs.count }}, First: {{ v.docs|first }}</li></ul>
{% endfor %}

Now docs is a list of userdocs type. i.e. is an instance. So first filter returns me this instance. From this I need to extract it's id. How do I do that?

I tried {{ v.docs|first }}.id and various other futile trials.

Answer

Abdul Majeed picture Abdul Majeed · Apr 3, 2015

You can try this:

{{ v.docs.0 }}

Like arr.0

You can get elements by index (0, 1, 2, etc.).