Question

Given the code below, I want to get the latest 6 blogs using the backwards queries described here). For each of these blogs I need to get their associated photos.

There are 7 queries run to accomplish this and it seems like a lot. Is there any way I can optimise it?

class Blog(models.Model):
    title = models.CharField(max_length="150")
    pub_date = models.DateTimeField('Date published', null=True, blank=True)

class BlogImage(models.Model):
    image = models.ImageField(upload_to='img')
    parent_blog = models.ForeignKey(Blog)

items = Blog.objects.order_by('-pub_date')[:6]

my_list = list()
for item in items:
    tup = (item,item.blogimage_set.all())
    my_list.append(tup)

return  render(request, 'template.html',{'items': my_list})
Was it helpful?

Solution

Use prefetch_related to prefetch any items accross a multi-valued relation (many-to-many or reverse foreign-key relations).

items = Blog.objects.order_by('-pub_date').prefetch_related('blogimage_set')[:6]

This will reduce the amount of queries to 2, 1 for all the blogs, and 1 for all images related to any of the blogs.

(Documentation)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top