【发布时间】:2013-06-30 09:21:36
【问题描述】:
有没有办法检查 Django 模板中的空查询集?在下面的示例中,我只希望在有注释时显示 NOTES 标题。
如果我将 {% empty %} 放在 "for" 中,那么它会显示空标签内的任何内容,因此它知道它是空的。
我希望得到不涉及两次运行查询的东西。
{% if notes - want something here that works %}
NOTES:
{% for note in notes %}
{{note.text}}
{% endfor %}
{% endif %}
澄清:上面的示例“if notes”不起作用 - 即使查询集为空,它仍会显示标题。
这是视图的简化版本
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))
编辑:视图选择从多个表中选择。
【问题讨论】:
-
您确定它会运行两次查询吗?而且,一个简单的建议是“缓存”,但它不能回答您的问题。
-
我的问题不在于它运行了两次查询。我的例子不起作用。即使查询集为空,它也会显示标题。
-
请发表您的看法
-
为什么
{% if notes %}不起作用? -
notes是一个原始查询集,与常规查询集不同,它没有定义__nonzero__方法。因此,即使为空,它们也会评估为 True。 docs.python.org/2/reference/datamodel.html#object.__nonzero__