문제

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})
도움이 되었습니까?

해결책

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top