问题
I have a related query of limit 10 of an object. It's taking over 9s to load the whole page in development mode. When I'm not running the related query for loop on template, it only takes 1s to load. I'm quite confused what's going on in here! Please help me identify the problem/what I'm doing wrong here! Thanks in advance!
Here' my view file code -
related = News.objects.filter(
is_active=True,
status='public',
language=request.LANGUAGE_CODE,
category=news.category
).order_by('-published_at')[:10]
And here's the loop on template file -
{% for r in related %}
<li class="row mb-4">
<a href="{% url 'single_news' r.id %}" class="col-5">
<img src="{{ r.featured_image.url }}" alt="Image" class="rounded img-fluid">
</a>
<div class="col-7">
<a href="{% url 'single_news' r.id %}" class="no-underline">
<h6 class="mb-3 h5 text-charcoal">{{ r.heading }}</h6>
</a>
<div class="d-flex text-small">
<span class="text-muted ml-1">{{ r.published_at }}</span>
</div>
</div>
</li>
{% endfor %}
Here's the django-debug-ttolbar image of the query time -
回答1:
How many News objects are there in the db? If you have many of them, and you don't have indexes on the columns you in your underlying where
clause or order_by
clause, it could take a long time to get those 10 News items. Do you have access to the database directly? I'd try the SQL of that query and see if the query takes a long time:
SELECT * FROM content_news WHERE is_active=1 AND status='public' AND language='bn' ORDER_BY published_at DESC
I notice the query in the screenshot doesn't have the category=news.category
clause. Is category a foreign key? If so you may want to use select_related
to efficiently retrieve it.
Hope that helps, happy coding!
来源:https://stackoverflow.com/questions/62110378/django-template-query-for-loop-render-taking-too-much-time