如何在django中使用带有GenericForeignKey的select_related?

时间:2014-12-04 10:42:42

标签: python django

我遇到的情况是,特定类的大量对象正在迭代,并且它们需要花费大量时间进行处理,因为我无法使用select_related预先选择数据。

有问题的课程如下所示

from django.contrib.contenttypes.models import ContentType
from django.db import models

class Offer(models.Model):
    ...
    object_id = models.PositiveIntegerField(db_index = True)
    content_type = models.ForeignKey(ContentType, db_index = True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    ...

我尝试使用如下所示的select_related,但它显然不起作用

offerList = Offer.objects.select_related('content_type', "content_object"
    ).filter(content_type=ContentType.objects.get_for_model(SomeObject),
    object_id=someobject.id)

那么,如何在django中使用select_related和GenericForeignKey?

1 个答案:

答案 0 :(得分:16)

您正在寻找的不是select_related。它是prefetch_related

  

支持预取GenericRelation和GenericForeignKey。

因此,your base command将是:

Offer.objects.all().prefetch_related('content_object')