在Wagtail

时间:2017-11-25 15:28:59

标签: python django wagtail

我在网站项目中使用Wagtail v1.13.1。我试图优化数据库查询...

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循环中输出产品卡。每张产品卡都有以下标签:

{% image product.main_image fill-600x300 %}

但仍然为每个图像单独调用db。

模型以这种方式连接:

ProductPage --fk - > wagtailimages.Image < - fk-- wagtailimages.Rendition

问题是:预取再现并消除重复数据库查询的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个。

prefetch_related('main_image__rendition_set')

这假设图像模板标签可以正确使用预取值。