Django Templating: how to access properties of the first item in a list

后端 未结 4 366
粉色の甜心
粉色の甜心 2020-12-12 20:28

Pretty simple. I have a Python list that I am passing to a Django template.

I can specifically access the first item in this list using

{{ thelist|f         


        
相关标签:
4条回答
  • 2020-12-12 20:43

    If you're trying to access a manytomany field, remember to add all, so it will look like object.m2m_field.all.0.item_property

    0 讨论(0)
  • 2020-12-12 20:47

    You can combine the with template tag with the first template filter to access the property.

    {% with thelist|first as first_object %}
        {{ first_object.propertyname }}
    {% endwith %}
    
    0 讨论(0)
  • 2020-12-12 20:49

    You can access any item in a list via its index number. In a template this works the same as any other property lookup:

    {{ thelist.0.propertyName }}
    
    0 讨论(0)
  • 2020-12-12 20:57

    a potentially clearer answer/syntax for accessing a ManyToManyField property in an object list provided to the django template would look like this:

    {{ object_list.0.m2m_fieldname.all.0.item_property }}
    
    0 讨论(0)
提交回复
热议问题