4

I was using the count method on a queryset context variable more than once in a template, so I decided to store it in a reusable variable:

{% with album.photograph_set.count as numPhotos %}
    <title>My title with {{ numPhotos }} in it</title>
    <span>I use {{ numPhotos }} here, too</span>
{% endwith %}

The numPhotos variable always seems to be blank, though replacing it with album.photograph_set.count inline still returns the appropriate value. I also tried using the {% with numPhotos=album.photograph_set.count %} syntax but it exhibits the same behavior. I use the {% with ... as ... %} syntax elsewhere in my code and it works as expected.

Any help is appreciated.

4

1 回答 1

4

如果photograph_set 是ForeignKeyField 的反向关系或者它是ManyToManyField,你需要做

{% with album.photograph_set.all.count as numPhotos %}
于 2013-08-13T11:41:09.530 回答