如何为已经获取的对象列表预取相关对象?

时间:2017-06-04 19:49:46

标签: django django-models django-orm

我在主页上显示7个随机对象。为此,我使用基于this answer的解决方案:

sectionDate

如果我将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'))方法,则每次为每个产品预取1张照片。这并不奇怪。我是否可以在获取产品后手动预取相关对象?

1 个答案:

答案 0 :(得分:1)

令我惊讶的是,有一个legal way。记录,即。你只需要添加:

prefetch_related_objects(random_products, Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk')))