1

私はすべての問題ノートを取得する次のコードを持っています。

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

最初の問題メモだけを取得するにはどうすればよいですか? テンプレートでそれを行う方法はありますか?

4

3 に答える 3

4

ビューで:

context["problem_tasks"] = Task.objects.filter(is_problem=True)
# render template with the context

テンプレートでは:

{{ problem_tasks|first }}

firstテンプレート フィルタリファレンス


他の問題のあるタスクがまったく必要ない場合 (2 番目から最後まで) はさらに良いでしょう:

context["first_problem_task"] = Task.objects.filter(is_problem=True)[0]
# render template with the context

テンプレート:

{{ first_problem_task }}
于 2013-08-02T23:29:04.727 に答える
2

テンプレート内のすべてのタスクが別の場所に必要であると仮定します。

再利用可能なカスタム フィルター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 %}

それが役立つことを願っています。

于 2013-08-02T22:38:33.470 に答える
0

ループで次のコードを使用します。

{% if forloop.counter == 1 %}{{ n }}{% endif %}
于 2013-08-03T00:47:30.790 に答える