如何优化此向后相关对象查询?(django)
给出下面的代码,我想使用下面描述的反向查询获得最新的6个博客。对于这些博客中的每一个,我都需要获得它们的相关照片 有7个查询运行来完成这一点,这似乎是很多。有什么方法可以优化它吗如何优化此向后相关对象查询?(django),django,django-queryset,Django,Django Queryset,给出下面的代码,我想使用下面描述的反向查询获得最新的6个博客。对于这些博客中的每一个,我都需要获得它们的相关照片 有7个查询运行来完成这一点,这似乎是很多。有什么方法可以优化它吗 class Blog(models.Model): title = models.CharField(max_length="150") pub_date = models.DateTimeField('Date published', null=True, blank=True) class Blo
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})
使用
prefetch\u related
预取多值关系(多对多或反向外键关系)中的任何项
这将使查询量减少到2,所有博客的查询量为1,与任何博客相关的所有图像的查询量为1
()
items = Blog.objects.order_by('-pub_date').prefetch_related('blogimage_set')[:6]