Завершение цикла 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"
. (Придуманный пример)
Что я хочу:
- Check the
requests
list to determine if any of the elements in the list satisfies the condition ofr.status == "Active"
(or whatever condition, this is just an example) - 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. - 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 %}