Django模板查询循环渲染花费太多时间 [英] Django template query for loop render taking too much time

查看:161
本文介绍了Django模板查询循环渲染花费太多时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象限制10的相关查询。在开发模式下加载整个页面需要9秒钟的时间。当我不在模板上运行相关的循环查询时,只需1秒即可加载。我很困惑这里发生了什么!请帮助我确定问题/我在做什么错!

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 %}

这是查询时间的django-debug-ttolbar图像-

Here's the django-debug-ttolbar image of the query time -

推荐答案

数据库中有多少个News对象?如果其中有很多,并且您的基础 where 子句或 order_by 子句,可能需要很长时间才能获得这10个新闻项目。您可以直接访问数据库吗?我会尝试查询该查询的SQL,看看查询是否需要很长时间:

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

我注意到该查询该屏幕截图没有 category = news.category 子句。类别是外键吗?如果是这样,您可能想使用 select_related 来有效地检索它。

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!

这篇关于Django模板查询循环渲染花费太多时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆