如何只获取模板中的第一个对象

时间:2013-08-02 22:18:41

标签: django django-templates

我有以下代码,我会收到所有问题说明。

{% for n in task.task_notes.all %}
    {% if n.is_problem %}
        <li>{{ n }}</li>
    {% endif %}
{% endfor %}

如何获得第一个问题提示?有没有办法在模板中做到这一点?

3 个答案:

答案 0 :(得分:4)

在视图中:

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 }}

答案 1 :(得分:1)

假设您需要模板中的所有其他任务。

您可以制作可重复使用的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 %}

希望有所帮助。

答案 2 :(得分:0)

在循环中使用此代码:

{% if forloop.counter == 1 %}{{ n }}{% endif %}
相关问题