2017-11-25 1 views
0

私のウェブサイトプロジェクトにWagtail v1.13.1を使用しています。私はWagtailで画像タグを使用すると、多くの重複したクエリが発生する

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ループの中で、製品のカードを出力しています... DBのクエリを最適化しようとしています。各商品カードには次のタグがあります。

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

ただし、画像ごとにdbを別々に呼び出しています。

モデルがこのように接続されています

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

質問です:何ですかレンディションをプリフェッチし、重複したdbクエリを排除する適切な方法?

答えて

0

これを試してください。

prefetch_related('main_image__rendition_set') 

これは、イメージtemplatetagがプリフェッチされた値を正しく使用できることを前提としています。

+0

申し訳ありませんが、レンディションモデルがfkをイメージモデルにこのように定義していることを忘れてしまいました:image = models.ForeignKey(Image、related_name = 'renditions'、on_delete = models.CASCADE) – romengrus

関連する問題