我有以下代码
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
prefetch = ['vendor', 'picture']
context['most_popular_products'] = Product.objects.filter(is_popular=True)[:5].prefetch_related(*prefetch)
context['coming_soon_products'] = Product.objects.filter(is_coming_soon=True)[:5].prefetch_related(*prefetch)
context['recent_products'] = Product.objects.all()[:5].prefetch_related(*prefetch)
return context
如您所见,有5个最新most_popular
,coming_soon
和recent
个产品分别有3个电话。
有没有办法减少数据库调用次数?
我想构建单个查询,如
popular, coming_soon, recent = Product.objects.filter...and.so.on
有什么想法吗?感谢
答案 0 :(得分:1)
我不这么认为..但你可以使用一个查询集并从中过滤。
即。
products = Product.objects.all()
recent_products = products[:5]
coming_soon_products = products.filter(is_coming_soon=True)
most_popular_products = porducts.filter(is_popular=True)