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 %}

これは正しい方法ですか、それともどういうわけか2つのクエリを回避できますか?

ありがとう。

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 %}

emptyforループ内で使用できるタグもありますが、それはおそらくあなたの例には当てはまりません。

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 に答える