0

这是我目前必须检查作者是否在相关照片模型中有一些照片:

{% if author.photo_set.count > 0 %}
<h2>...</h2>
<div style="clear: both;"></div>
<div class="author_pic">
    {% for photo in author.photo_set.all %}
        <img src="..." />
    {% endfor %}
    <div style="clear: both;"></div>
</div>
<div style="clear: both;"></div>
{% endif %}

这是正确的方法还是我可以以某种方式避免两个查询?

谢谢。

4

2 回答 2

4

您可以使用with标签来避免多次查询。

{% with author.photo_set.all as photos %}
    {% if photos %}
    <h2>...</h2>
    <div style="clear: both;"></div>
    <div class="author_pic">
        {% for photo in photos %}
            <img src="..." />
        {% endfor %}
        <div style="clear: both;"></div>
    </div>
    <div style="clear: both;"></div>
    {% endif %}
{% endwith %}

您还empty可以在 for 循环中使用标签,但这可能不适用于您的示例。

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for-empty

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>Sorry, no athlete in this list!</li>
{% endfor %}
<ul>
于 2012-12-24T05:35:06.850 回答
1

正如@pyrospade 建议的那样,您可以查看照片对象是否存在。或者您也可以检查 photo_set 列表的长度(检查长度模板标签),如下所示:

{% if author.photo_set.all|length > 0 %}
    <h2>...</h2>
    <div style="clear: both;"></div>
    <div class="author_pic">
        {% for photo in author.photo_set.all %}
            <img src="..." />
        {% endfor %}
        <div style="clear: both;"></div>
    </div>
    <div style="clear: both;"></div>
{% endif %}
于 2012-12-24T06:48:10.760 回答