Django模板:检查空查询集

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 %}.这个对我有用.

  • 不要将queryset用作布尔值:而不是`if queryset:`use` if queryset.exists():`记住,查询集是惰性的,如果使用queryset作为布尔值,对数据库的不适当查询将进行.@Chris方法更好 (4认同)
  • 也适用于我,我更喜欢这个`.count`,因为它会发出一个`select count(*)`查询,而我认为这会缓存查询集,如果有的话. (2认同)
  • 感谢@KishorPawar解决方案,虽然在模板中它没有括号:`if queryset.exists`. (2认同)

Pet*_*per 6

不幸的是,您在使用原始查询集时陷入困境 - 他们错过了许多有用的行为。

您可以将原始查询集转换为视图中的列表:

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)


Sim*_*ser 5

在您的视图中检查是否notes为空.如果是,那么你通过None:

{"notes": None}
Run Code Online (Sandbox Code Playgroud)

在您的模板中,您可以{% if notes %}正常使用.

  • 我认为最好执行“notes.count()” - 最后我检查“len(notes)”从数据库中提取每条记录,而 count 只是发出计数查询。 (2认同)

mat*_*ino 4

关于什么:

{% 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)