How can i optimise this backwards related objects query? (django)

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})

Answers


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)


Need Your Help

How to change facebook app icon

facebook

I can't seem to find the right location of the settings since facebook redesigned admin panel ... screenshots appreciated , I can only change screenshots and banners but not the app icon itself

Calling shell script from Java by giving a relative path of script location

java web-applications

I am working on a project wherein I have to call my shell script stored at the location where my java files reside.I am currently calling the shell script by giving a hard-coded (absolute) path.I w...