Home > front end >  Django how access result from queryset in template from index
Django how access result from queryset in template from index

Time:12-22

I have a queryset result in a template:

{% for image in product.productimages_set.all %}
<img src="{{ image.image_file.url }}"/>
{% endfor %}

How could I access a index of that object in a template, ie:

<img src="{{ product.productimages_set.all.0 }}"/>

CodePudding user response:

Can access index by using the forloop.counter

{% for image in product.productimages_set.all %}
{% if forloop.counter == 0 %}
<img src="{{ image.image_file.url }}"/>
{% else %}
{% if forloop.counter == 1 %}
<img src="{{ image.image_file.url }}"/>
{% endif %}
{% endfor %}

Django supports using .first() and .last() on querysets:

# Query from the  view.py 
first_element = Product.objects.first()
last_element =  Product.objects.last()

products = list(Product.objects.all())
first_element = products[0]
last_element = products[-1]

# Query from HTML
{{ product.productimages_set.all.first.image_file.url }}
{{ product.productimages_set.all.last.image_file.url }}
  • Related