【问题标题】:Many duplicate queries when using image tag in Wagtail在 Wagtail 中使用图像标签时出现许多重复查询
【发布时间】:2017-11-25 15:28:59
【问题描述】:

我在我的网站项目中使用 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 wagtailimages.Rendition

问题是:预取演绎版和消除重复数据库查询的正确方法是什么?

【问题讨论】:

    标签: python django wagtail


    【解决方案1】:

    试试这个。

    prefetch_related('main_image__rendition_set')
    

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

    【讨论】:

    • 抱歉,忘了说 Rendition 模型是这样定义 fk 到 Image 模型的:image = models.ForeignKey(Image, related_name='renditions', on_delete=models.CASCADE)
    猜你喜欢
    • 2021-03-16
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2016-01-24
    • 2018-04-25
    相关资源
    最近更新 更多