我在主页上显示7个随机对象。为此,我根据此答案使用解决方案:
class ProductManager(models.Manager):
def random(self, n_products, filter={}, select_related=None):
n_products_total = self.filter(**filter).count()
if n_products_total == 0:
return []
r = [
self.random_impl(n_products_total, filter, select_related)
for i in range(n_products)
]
return [p for p in r if p is not None]
def random_impl(self, n_products, filter, select_related=None):
random_index = randint(0, n_products - 1)
try:
return self.filter(**filter)
.select_related(select_related)[random_index]
except IndexError:
return None
random_products = Product.objects.random(
7, filter={'enabled': True}, select_related='category'
)
如果我将prefetch_related=Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk'))
传递给random_impl
方法,则每次产品一次预取1张照片。这不足为奇。我可以在获取产品后手动预取相关对象吗?
令我惊讶的是,有一种法律方式。记录在。您只需要添加:
prefetch_related_objects(
random_products,
Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk')),
)