User and Score models I have a couple of models - User &amp; Score. I am displaying data from those models to my template. Data from Score is filtered based on data from User. I am using nested for loops and an if condition within the template to get my desired result. However, I want to know if there is a better way of coming up with the same result because once the data gets huge by number, the nested for loop is going to use up a lot of time and resource.

models.py

class User(models.Model):
    name = models.CharField(max_length=20)
    age = models.IntegerField()

class Score(models.Model):
    user = models.ForeignKey('User')
    subject = models.CharField(max_length=20)
    score = models.IntegerField()


views.py

def Home(request):
    users = User.objects.all()
    scores = Score.objects.all()
    return render(request, "home.html", {'users': users, 'scores': scores})


home.html (template)

{% for user in users %}
    {% for score in scores %}
    {% if score.user == user %} {{ user }} -- {{ score.subject }} -- {{ score.score }} &lt;br&gt;{% endif %}
    {% endfor %}
    {% endfor %}


Result




Michel -- Physics -- 80 
Michel -- Chemistry -- 90 
Zarif -- Physics -- 100 
Zarif -- Biology -- 80



This question is a simplified version of this (Django ORM usage in template). If you can, maybe answer over there too!
Your nested loop seems to serve the purpose of grouping the output by user.
Since Score has a link to User,
you can achieve the same effect by getting the scores ordered by the user field, like this:

def Home(request):
    scores = Score.objects.order_by('user')
    return render(request, "home.html", {'scores': scores})


And then in the template you can eliminate one for and one if:

{% for score in scores %}
{{ score.user }} -- {{ score.subject }} -- {{ score.score }} &lt;br&gt;
{% endfor %}