[Django]-Page is loading very slow in django

4👍

This is a common N+1 problem where you fetch all the Lecturers in one database query, but then for each Lecturer, you make extra queries to fetch the lecture objects, and the faculty objects related to it.

You can boost efficiency here with .select_related(…) [Django-doc] for one-to-one relations and many-to-one relations, and .prefetch_related(…) [Django-doc] for one-to-many and many-to-many relations. So here you can work with:

class Index(generic.ListView):
    template_name='home.html'
    model = Lecturer
    context_object_name = 'lecture_list'
    queryset = Lecturer.objects.select_related(
        'faculty'
    ).prefetch_related('lecture').order_by('lecturer')

Since this is a ListView, there is no need to add the queryset to the context yourself, you can specify the name of the variable where you pass the queryset with the context_object_name attribute [Django-doc].

Leave a comment