【问题标题】:reduce django db calls减少 Django 数据库调用
【发布时间】:2012-07-30 01:33:31
【问题描述】:

我注意到我的 django 代码经常使用完全相同的查询调用我的数据库。

我了解,当我实际需要数据显示在页面上或进行评估时,会产生 db hit。但是,我的模板代码如下所示:

模板:

{% if item.listing %}
        {{ item.name }} text <strong>{{ item.listing|lowestprice }}</strong>  more text
{% else %}
        {{ item.name }} even more text
{% endif %}
     ....
{% for listed_item in item.listing %}
     ....
{% endfor %}

自定义过滤器:

def lowestprice(value):
   try:
      val = unicode(value[0].price) + unicode(value[0].symbol)
      return val
   except:
      return "not available"

这段代码在我的数据库中命中了 3 次。首先是模板{% if .. %},其次是我的自定义过滤器,第三是{% for %} 循环。

listing 是我的模型类的一种方法,它返回一个带有一些非常昂贵的连接的原始 SQL 查询集。

def listing(self):
    return Universe.objects.raw("ONE HELL OF A QUERY")

如何减少我的代码只访问数据库一次?

编辑:使用with 有效,但是否可以避免数据库命中自定义过滤器?

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    您应该使用with 执行一次昂贵的查询并将其存储在上下文中。

    {% with item.listing as item_listing %}
       {% if item_listing %} ... {% endif %} ... etc ...
    {% endwith %}
    

    【讨论】:

    • with 是否仅限于一个block 中使用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2011-09-24
    • 2015-09-25
    • 2020-06-02
    • 1970-01-01
    • 2019-09-25
    • 2013-05-20
    相关资源
    最近更新 更多