robos85
robos85

Reputation: 2554

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?

Upvotes: 1

Views: 849

Answers (2)

Dick
Dick

Reputation: 1238

What you are looking for is an efficient way to do reverse foreign-key lookups. A generic approach is:

qs = MyRelatedObject.objects.all()
obj_dict = dict([(obj.id, obj) for obj in qs])
objects = MyObject.objects.filter(myrelatedobj__in=qs)
relation_dict = {}
for obj in objects:
    relation_dict.setdefault(obj.myobject_id, []).append(obj)
for id, related_items in relation_dict.items():
    obj_dict[id].related_items = related_items

I wrote a blogpost about this a while ago, you can find more info here: http://bit.ly/ge59D2

Upvotes: 1

Kamran Khan
Kamran Khan

Reputation: 9986

How about:

Using Django's session framework; load list request.session['lstTechnology'] = listOfTechnology on startup. And use session in rest of the app.

Upvotes: 0

Related Questions