Home > Blockchain >  How to reduce for loops in html in Django?
How to reduce for loops in html in Django?

Time:12-26

I tried the following for loops and if statements in django html, but it takes so long to load one page. First, here is the html:

                       {% for time in TIME_CHOICES %}

                        <tr >
                            <td >
                                {{time}}
                            </td>
                            {% for each_date in dates_in_month %}
                            {% if each_date not in weekends %}
                                {% for class in classes %}
                                 <h1>class</h1>
                                {% endfor %}
                            {% else %}
                            <td >
                                <ul  style="font-size: 0.70rem; line-height: 0.85rem;">
                                    <li>-----</li>
                                    <li>--(--)</li>
                                </ul>
                            </td>
                            {% endif %}
                            {% endfor %}
                        </tr>

                        {% endfor %}

I think this is because I have too many for loops and if statements happening in my html. Is there anyway I can increase the speed? Or is there any way I can do the same thing in django views(I am using generic list view, so I need some code for the get_context_data)? Thank you, and please leave any questions you might have.

CodePudding user response:

It's hard to say where is a performance problem in your code. Loops in html shouldn't take a lot of time. Maybe you have a lot of db queries or run some heavy methods.

Try to investigate what part of your code is really slow. You can you Silk profiler for this

Silk is a live profiling and inspection tool for the Django framework. Silk intercepts and stores HTTP requests and database queries before presenting them in a user interface for further inspection:

Installation

pip install django-silk

In settings.py add the following:

MIDDLEWARE = [
    ...
    'silk.middleware.SilkyMiddleware',
    ...
]

INSTALLED_APPS = (
    ...
    'silk'
)

Try to find the method that takes the most part of time and optimize it. Also, you can add Silk's result to your question. It helps to figure out the problem

CodePudding user response:

It is always better to reduce database hits. In your code you are hitting database in an iteration so if the loop run for 1000 times it will hit database 1000 times this can be reduced to just one query like this:

classes = Class.objects.filter(
      teacher=teacher, date__in=[each_date for each_date in dates_in_month 
                                 if each_date not in weekends]
      ).order_by('date','time')

then you can iterate the classes queryset to continue with the rest of the code.

Also make your code more readable right now it is a messy.

  • Related