[Answer]-How to loop over two querysets at the same time?

1👍

You can look up the related comments for a story by using the “related manager” (more info about it here in the Django documentation).

The code would look like this:

{% for story in all_user_stories %}
  {{ story.title }}
  {% for comment in story.comment_set.all %}
    {{ comment.comment_text }}
  {% endfor %}
{% endfor %}

It should also be possible to use the “related name” story.commments instead of story.comment_set when looking up the comments for a specific story:

{% for story in all_user_stories %}
  {{ story.title }}
  {% for comment in story.comments.all %}
    {{ comment.comment_text }}
  {% endfor %}
{% endfor %}
👤HAL

Leave a comment