我有以下代码,在那里我得到了所有问题说明。
{% 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 %}
我怎样才能得到第一个问题说明?有没有办法在模板中做到这一点?
在视图中:
context["problem_tasks"] = Task.objects.filter(is_problem=True)
# render template with the context
在模板中:
{{ problem_tasks|first }}
first
模板过滤器参考。
如果您根本不需要其他问题任务(从第二个到最后一个),那就更好了:
context["first_problem_task"] = Task.objects.filter(is_problem=True)[0]
# render template with the context
模板:
{{ first_problem_task }}
假设您在其他地方需要模板中的所有任务。
您可以制作一个可重用的自定义过滤器(看看first
过滤器实现顺便说一句):
@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 %}
希望有帮助。
在循环中使用此代码:
{% if forloop.counter == 1 %}{{ n }}{% endif %}