如何在Django中使用与GenericForeignKey相关的select\u?

2024-05-19 14:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一种情况:一个特定类的大量对象被迭代,它们需要花费大量的时间进行处理,因为我不能使用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_相关的,但显然不起作用

^{pr2}$

那么,在django中,如何将select_related与GenericForeignKey一起使用呢?在


Tags: djangofromimportidtruedbindexobject
1条回答
网友
1楼 · 发布于 2024-05-19 14:30:55

它不是你要找的select_related。它是prefetch_related,它

supports prefetching of GenericRelation and GenericForeignKey.

因此,your base command将是:

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

相关问题 更多 >