You should create the collection of filtered comments in your view, then include that in the template's context. Django's template philosophy is to make them as simple as possible which generally means no function calls (except for template tags and filters).
To make things a bit more efficient you should utilize prefetch_related
and Prefetch
. Checkout the docs on them for the best reference.
from django.db.models import Prefetch
posts = Post.objects.all().prefetch_related(
Prefetch(
'comments',
Comment.objects.select_related('user').order_by('-comment_posted_on')[:2],
to_attr='latest_comments',
)
)
Then in your template:
{% for comment in post.latest_comments %}
<p>{{ comment.user.username }}: {{ comment.description }}</p>
{% endfor %}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…