Python 这是检查对象在模板中是否没有相关对象的方法吗?
这是我目前必须检查的内容,作者是否在相关照片模型中有一些照片:Python 这是检查对象在模板中是否没有相关对象的方法吗?,python,django,Python,Django,这是我目前必须检查的内容,作者是否在相关照片模型中有一些照片: {% 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="..." />
{% 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 %}
{%if author.photo\u set.count>0%}
...
{author.photo_set.all%中的照片为%s}
{%endfor%}
{%endif%}
这是正确的方法还是我可以避免两个问题
谢谢。您可以使用
with
标记来避免多次查询
{%with author.photo\u set.all as photos%}
{%if照片%}
...
{%用于照片中的照片%}
{%endfor%}
{%endif%}
{%endwith%}
您还可以在for循环中使用empty
标记,但这可能不适用于您的示例
{运动员列表中运动员的百分比%}
- {{atternate.name}
{%empty%}
- 抱歉,此列表中没有运动员李>
{%endfor%}
您可以使用with
标记来避免多次查询
{%with author.photo\u set.all as photos%}
{%if照片%}
...
{%用于照片中的照片%}
{%endfor%}
{%endif%}
{%endwith%}
您还可以在for循环中使用empty
标记,但这可能不适用于您的示例
{运动员列表中运动员的百分比%}
- {{atternate.name}
{%empty%}
- 抱歉,此列表中没有运动员李>
{%endfor%}
作为@pyrospade suggsted,您可以查看照片对象是否存在。或者您也可以检查照片集列表的长度(检查模板标记),如下所示:
{% 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 %}
{%if author.photo_set.all | length>0%}
...
{author.photo_set.all%中的照片为%s}
{%endfor%}
{%endif%}
作为@pyrospade suggsted,您可以查看照片对象是否存在。或者您也可以检查照片集列表的长度(检查模板标记),如下所示:
{% 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 %}
{%if author.photo_set.all | length>0%}
...
{author.photo_set.all%中的照片为%s}
{%endfor%}
{%endif%}