2014-12-04 76 views
6

我有一种情况,其中大量的特定类的对象正在迭代,并且它们需要大量的时间来处理,因为我无法使用select_related预先选择数据。如何在django中使用select_related和GenericForeignKey?

有问题的类变为类似下面

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) 

所以,我怎么能使用select_related与GenericForeignKey在Django?

+0

的可能重复的[Django的:选择\ _related和GenericRelation](http://stackoverflow.com/questions/2939552/django-select-related -and-genericrelation) – 2014-12-11 10:52:12

回答

10

这不是select_related你在找什么。它是prefetch_related,其中

支持预取GenericRelation和GenericForeignKey。

因此,your base command将是:

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

相关问题