Завершение цикла for при выполнении определенного условия в Django с помощью шаблонов

Похожий вопрос был задан ранее, но предложенные решения не сработали для меня.

Допустим, я получаю список из django views, например:

context['requests'] = requests

В шаблоне:

{% for r in requests %}
    {% if r.status == "Active" %}
        //do A
    {% else %}
        //do B
    {% endif %}
{% endfor %}

Список requests имеет 10 элементов, один из которых удовлетворяет условию r.status == "Active". (Придуманный пример)

Что я хочу:

  1. Check the requests list to determine if any of the elements in the list satisfies the condition of r.status == "Active" (or whatever condition, this is just an example)
  2. If some element in the list has the status Active the for loop will execute only one iteration, run the //do A code and then the loop will finish/break.
  3. If no element in the list has the status Active, the for loop will execute the //do B once and then break.

Я немного запутался и не знаю, есть ли другой тег по умолчанию для выполнения такого типа операций в Django

Вы можете проверить, активен ли какой-либо Request объект модели status в представлении с помощью .exists() метода.

Например:

requests = Request.objects.all() 
context['requests'] = requests
context["has_active"] = Request.objects.filter(status="active").exists()

  # template
  {% if has_active %}
      // do A
  {% else %}
      //do B 
  {% endif %} 
Вернуться на верх