2014-03-06 22 views
0

根据下面的代码,我想使用描述为here的向后查询来获得最新的6个博客)。对于这些博客中的每一个,我都需要获取他们的相关照片。如何优化这个向后相关的对象查询? (django)

有7个查询运行来实现这一点,它似乎想了很多。有什么办法可以优化它吗?

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

回答

2

使用prefetch_related预取翻过一个多值关系(很多一对多或反向外键关系)的物品。

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

这会将查询数量减少到2,1对于所有博客,对于与任何博客相关的所有图像都会减少1。

Documentation

+0

正是我在找的东西。谢谢! – rix