Sunday, February 27, 2011

How to reduce DB queries?

Models:
class Technology(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)

class Site(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    technology = models.ManyToManyField(Technology, blank=True, null=True)

Views:
def portfolio(request, page=1):
    sites_list = Site.objects.select_related('technology').only('technology__name', 'name', 'slug',)
    return render_to_response('portfolio.html', {'sites':sites_list,}, context_instance=RequestContext(request))

Template:
{% for site in sites %}
<div>
    {{ site.name }},
    {% for tech in site.technology.all %}
        {{ tech.name }}
    {% endfor %}
</div>
{% endfor %}

But in that example each site makes 1 additional query to get technology list. Is there any way to make it in 1 query somehow?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment