[Answered ]-How to limit a collection of objects related on a foreign key in Django Templates?

1👍

{% for task in tasks %}
  {% for comment in task.comment_set.all|slice:"5" %}
    {{ comment }}
  {% endfor %}
{% endfor %}

1👍

You don’t. You should not do “real work” in a template, this breaks the MVC pattern.

Do the real work in the view, and pass the data to the template (using the context dictionary).

def handle_comments(request):
    tasks = Task.objects.all()
    comments = {}
    for task in tasks:
      comments[task] = task.comment_set.all()[:5]
    return render_to_response('commenting.html', {'comments': comments})

You can then iterate over the comments in your template:

{% for task, task_comments in comments.items %}{{ task }}{% endfor %}
👤Tommy

Leave a comment