Malik Zohaib Mustafa
Malik Zohaib Mustafa

Reputation: 45

Django templates avoid loop

I am working on a project and I have a slight confusion.

The Django Template index.html has following code:

  <div class="carousel-item active">
      {% for i in products|slice:"0:"%}
        <div class="col-xs-3 col-sm-3 col-md-3">
          <div class="card" style="width: 17rem;">
              <div class="card-body">
              {% for img in i.images.all %}
                  {% if forloop.counter == 1 %}
                  <img src={{img.img_url}} class="card-img-top" alt="...">
                  {% endif %}
               {% endfor %}

                <h6 class="card-title">{{i}}</h6>
                   {% for skus in i.skus.all %}
                                        {% if forloop.counter == 1 %}
                  <h6 class="card-price">{{skus.price}} {{skus.currency}}</h6>
                                        {% endif %}
               {% endfor %}
                <a href="#" class="btn btn-primary">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 the 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?

Upvotes: 1

Views: 84

Answers (2)

Nicolas Appriou
Nicolas Appriou

Reputation: 2331

You may be looking for the first queryset method:

<div class="card-body">
  <img src={{i.images.first().img_url}} class="card-img-top" alt="...">
</div>

Upvotes: 0

shah sawood
shah sawood

Reputation: 414

You can achieve by using either with tag to set a variable or direclty us as:

{% with skus=i.skus.first %}
    <h6 class="card-price">{{skus.price}} {{skus.currency}}</h6
{% endwith %}

or

<h6 class="card-price">{{i.skus.first.price}} {{i.skus.first.currency}}</h6

Upvotes: 1

Related Questions