【问题标题】:How to only get first object in template如何只获取模板中的第一个对象
【发布时间】:2013-08-04 07:36:27
【问题描述】:

我有以下代码,我可以在其中获得所有问题说明。

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

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

【问题讨论】:

  • 不是——我只得到第一个具有is_problem=True 的项目。不是 for 循环中的第一个。
  • 你可以在你的视图中过滤(即task=Task.objects.filter(is_problem=True),我猜),然后使用彼得的建议
  • 是的,那是进行过滤的更好地方——更高效。或者在task 上添加一个返回过滤后的qs 的方法并使用|first

标签: django django-templates


【解决方案1】:

在视图中:

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

【讨论】:

    【解决方案2】:

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

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

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      在循环中使用此代码:

      {% if forloop.counter == 1 %}{{ n }}{% endif %}
      

      【讨论】:

        猜你喜欢
        • 2017-06-27
        • 2018-06-06
        • 2013-03-24
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 2021-12-24
        • 2022-11-27
        相关资源
        最近更新 更多