page is loading very slow in django

Viewed 1863

Hello I have a webproject which I am hosting, the problem is that a specific page is loading very slow. The reason is I guess the Jquery code where I am iterating through the lectures and I have more then 1200 lectures. I normally showed all lectures and filtered them with searching and then I thought it could be faster if I show nothing and only show it when someone is searching but it is still slow. Here is my html. Thank you in advance.

html

{% extends "base.html" %}
{%block content%}
{% load crispy_forms_tags %}

<div class="container"><h1 style="text-align:center;">Not Dağılımları</h1>
    <hr>
</div>
<div class="container">

        <div class="form-group pull-right">
    <input type="text" class="search form-control" placeholder="Ara">
        </div>
        <span class="counter pull-right"></span>
        <table style="background-color:white;"class="table table-hover results">
    <thead>
        <tr>
        <th >Hoca</th>
                <th>Fakülte</th>
        <th >Ders</th>
        </tr>
        <tr class="warning no-result">
        <td><i class="fa fa-warning"></i> Sonuç Yok</td>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

</div>




<script>
$(document).ready(function(){
        $(".search").keyup(function () {
            $('tbody').find('tr').remove();
            var searchTerm = $(".search").val().toLowerCase();
            if (searchTerm.length>2){
            list=[]
            {%for lec in lecturer_list%}
            if( '{{lec}}'.toLowerCase().includes(searchTerm)){
                $('tbody').append('<tr><td><p><a style="text-decoration:none;color:#002855;" href="{% url 'distribution:lecturer_distribution' slug=lec.slug%}">{{lec.lecturer}}</a></p></td><td><p>{{lec.faculty}}</p></td><td style="color:white;">{%for ders in lec.lecture.all%}<a style="text-decoration:none;color:#002855;" href="{% url 'distribution:lecture_distribution' slug=ders.slug%}">{{ders.lecture}}</a>,{% endfor%}</td></tr>');
      }

            {%endfor%}
        }
        });
});

</script>

{% endblock content%}

EDIT here is my lecturer model

class Lecturer(models.Model):
    lecturer=models.CharField(max_length=128,blank=False)
    lecture=models.ManyToManyField(Lecture,blank=True)
    faculty=models.ForeignKey('Department', on_delete=models.CASCADE, related_name='department_for_lecturer')
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = self.slug or slugify(self.lecturer)
        super().save(*args, **kwargs)

    def get_lectures(self):
        return ",".join([str(p) for p in self.lecture.all()])

    def __str__(self):
        return self.lecturer

    class Meta:
        ordering = ['lecturer']

views.py

class Index(generic.ListView):
    template_name='home.html'
    models=Lecturer
    queryset = Lecturer.objects.all()


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['lecturer_list'] = Lecturer.objects.order_by('lecturer')
        return context
1 Answers

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].

Related