I am working on a project and jhave a slight confusion.
The Djago Template index.html has following code:
<div >
{% for i in products|slice:"0:"%}
<div >
<div style="width: 17rem;">
<div >
{% for img in i.images.all %}
{% if forloop.counter == 1 %}
<img src={{img.img_url}} alt="...">
{% endif %}
{% endfor %}
<h6 >{{i}}</h6>
{% for skus in i.skus.all %}
{% if forloop.counter == 1 %}
<h6 >{{skus.price}} {{skus.currency}}</h6>
{% endif %}
{% endfor %}
<a href="#" >Add to Cart </a>
</div>
</div>
</div>
{% endfor %}
</div>
In this code , Is there a way to eliminate the {% for skus in i.skus.all %}
The all tag is getting all objects but I am restricting the loop to run only one time through if condition so that I can only get the first item.
Is there a way to eliminate the loops that have .all in them and restrict the statement to run only one time though any other way.
CodePudding user response:
Are you looking for the first
queryset method ?
<div >
<img src={{i.images.first().img_url}} alt="...">
</div>
CodePudding user response:
You can achieve by using either with
tag to set a variable or direclty us as:
{% with skus=i.skus.first %}
<h6 >{{skus.price}} {{skus.currency}}</h6
{% endwith %}
or
<h6 >{{i.skus.first.price}} {{i.skus.first.currency}}</h6