在Wa中使用图像标签时,许多重复的查询 [英] Many duplicate queries when using image tag in Wagtail
问题描述
我正在将Wagtail v1.13.1用于我的网站项目.我正在尝试优化数据库查询...
I'm using Wagtail v1.13.1 for my website project. I'm trying to optimize db queries...
models.py
class ProductPage(Page):
...
main_image = models.ForeignKey(
'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', blank=True, null=True
)
class ProductIndexPage(Page):
...
def get_context(self, request, *args, **kwargs):
context = super(ProductsIndexPage, self).get_context(request)
all_products = ProductPage.objects\
.prefetch_related('main_image__renditions')\
.live()\
.public()\
.descendant_of(self)\
.order_by('-first_published_at')
paginator = Paginator(all_products, 10)
page = request.GET.get('page')
try:
products = paginator.page(page)
except PageNotAnInteger:
products = paginator.page(1)
except EmptyPage:
products = paginator.page(paginator.num_pages)
context['products'] = products
return context
product_index_page.html
我正在for循环中输出产品卡.每个产品卡都有以下标签:
I'm outputting product card in a for loop. Each product card has this tag:
{% image product.main_image fill-600x300 %}
但是仍然为每个图像分别调用db.
But still getting a separate call to db for each image.
以这种方式连接模型:
产品页面 --fk-> wagtailimages.Image <-fk-- wagtailimages.Rendition
ProductPage --fk--> wagtailimages.Image <--fk-- wagtailimages.Rendition
问题是:预取演绎并消除重复的数据库查询的正确方法是什么?
The question is: What is the proper way to prefetch renditions and eliminate duplicate db queries?
推荐答案
尝试一下.
prefetch_related('main_image__rendition_set')
这是假设图像模板标签可以正确使用预取的值.
This is assuming that the image templatetag can use the prefetched values correctly.
这篇关于在Wa中使用图像标签时,许多重复的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!