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

mu *_*u 無 9 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')
    ...
Run Code Online (Sandbox Code Playgroud)

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

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

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

rar*_*iru 16

这不是select_related你想要的.它是prefetch_related,它

支持预取GenericRelation和GenericForeignKey.

因此,您的基本命令将是:

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