0
我正在爲我的網站項目使用W v1草v1.13.1。我想優化的數據庫查詢...在W using中使用圖像標籤時的許多重複查詢
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
我在輸出產品的卡環。每個產品卡都有這個標籤:
{% image product.main_image fill-600x300 %}
但是仍然會對每個圖像分別調用db。
模特們以這種方式連接:
ProductPage --fk - >wagtailimages.Image < --fk-- wagtailimages.Rendition
的問題是:什麼是預取格式並消除重複的數據庫查詢的正確方法?
對不起,忘了提到Rendition模型以這種方式將fk定義爲Image模型:image = models.ForeignKey(Image,related_name ='renditions',on_delete = models.CASCADE) – romengrus