use*_*003 16 django django-templates
有没有办法检查Django模板中的空查询集?在下面的示例中,如果有注释,我只希望显示NOTES标题.
如果我在"for"中放置一个{%empty%},那么它会显示空标记内的任何内容,因此它知道它是空的.
我希望有一些不涉及运行查询的东西.
{% if notes - want something here that works %}
NOTES:
{% for note in notes %}
{{note.text}}
{% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
澄清:上面的示例"如果注释"不起作用 - 即使使用空查询集,它仍然显示标题.
这是视图的简化版本
sql = "select * from app_notes, app_trips where"
notes = trip_notes.objects.raw(sql,(user_id,))
return render_to_response(template, {"notes":notes},context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
编辑:视图选择从多个表中选择.
Tha*_*lin 22
看看{%empty%}标记.文档中的示例
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
链接:https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for-empty
小智 21
试试{% if notes.all %}.这个对我有用.
不幸的是,您在使用原始查询集时陷入困境 - 他们错过了许多有用的行为。
您可以将原始查询集转换为视图中的列表:
notes_as_list = list(notes)
return render_to_response(template, {"notes":notes_as_list},context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
然后在模板中将其检查为布尔值:
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
您也可以使用forloop.first以下方法在没有转换的情况下实现:
{% for note in notes %}
{% if forloop.first %}
Header
{% endif %}
{{ note.text }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
在您的视图中检查是否notes为空.如果是,那么你通过None:
{"notes": None}
Run Code Online (Sandbox Code Playgroud)
在您的模板中,您可以{% if notes %}正常使用.
关于什么:
{% if notes != None %}
{% if notes %}
NOTES:
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
{% else %}
NO NOTES AT ALL
{% endif %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22350 次 |
| 最近记录: |