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