我有以下代碼,在那裏我得到所有問題筆記。如何只在模板中獲得第一個對象
{% for n in task.task_notes.all %}
{% if n.is_problem %}
<li>{{ n }}</li>
{% endif %}
{% endfor %}
我怎麼會只得到的第一個問題的票子嗎?有沒有辦法在模板中做到這一點?
我有以下代碼,在那裏我得到所有問題筆記。如何只在模板中獲得第一個對象
{% for n in task.task_notes.all %}
{% if n.is_problem %}
<li>{{ n }}</li>
{% endif %}
{% endfor %}
我怎麼會只得到的第一個問題的票子嗎?有沒有辦法在模板中做到這一點?
假設您需要模板中的所有任務。
可以使一個可重複使用custom filter(看看first
過濾implementation BTW):
@register.filter(is_safe=False)
def first_problem(value):
return next(x for x in value if x.is_problem)
然後,用它在模板中是這樣的:
{% with task.task_notes.all|first_problem as problem %}
<li>{{ problem }}</li>
{% endwith %}
希望有所幫助。
在視圖:
context["problem_tasks"] = Task.objects.filter(is_problem=True)
# render template with the context
在模板:
{{ problem_tasks|first }}
first
模板濾波器reference。
甚至會更好,如果你不需要在所有其他問題的任務(從第二到最後一個):
context["first_problem_task"] = Task.objects.filter(is_problem=True)[0]
# render template with the context
模板:
{{ first_problem_task }}
使用此代碼在循環:
{% if forloop.counter == 1 %}{{ n }}{% endif %}
http://stackoverflow.com/quest可能的重複離子/ 3520554/get-first-item-of-queryset-in-template?rq = 1 –
不是真的 - 我只得到第一個具有'is_problem = True'的項目。不是for循環中的第一個。 – David542
你可以在你的視圖中過濾(即'task = Task.objects.filter(is_problem = True)',我猜測),然後使用Peter的建議 –