0
我在主頁上顯示7個隨機對象。對於我使用基於this answer溶液:如何預取相關對象以獲取已獲取列表的相關對象?
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張相片。這並不奇怪。產品已被提取後,可以手動預取相關對象嗎?