Joey
Joey

Reputation: 339

reduce django db calls

I noticed that my django code calls my database very often with the exact same queries.

I understand that a db hit is made when I actually need the data to display on a page or to evaluate. However, my template code looks like this:

template:

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

custom filter:

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

This code hits my db three times. First on template {% if .. %} second on my custom filter, third on the {% for %} loop.

listing is a method of my models class which is returning a raw SQL queryset with some very expensive joins.

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

How can I reduce my code to hit the db only once?

Edit: Using with works, but is it possible to avoid db hits on custom filters?

Upvotes: 0

Views: 150

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599866

You should use with to do the expensive query once and store it the context.

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

Upvotes: 2

Related Questions