相关疑难解决方法(0)

django:预取GenericForeignKey的相关对象

假设我有一个模型,Box一个GenericForeignKey指向任何一个Apple实例或Chocolate实例.AppleChocolate反过来,有ForeignKeys来FarmFactory,分别.我想显示一个Boxes 列表,我需要访问FarmFactory.如何在尽可能少的数据库查询中执行此操作?

最小的说明性示例:

class Farm(Model):
    ...

class Apple(Model):
    farm = ForeignKey(Farm)
    ...

class Factory(Model):
    ...

class Chocolate(Model):
    factory = ForeignKey(Factory)
    ...

class Box(Model)
    content_type = ForeignKey(ContentType)
    object_id = PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    ...

    def __unicode__(self):
        if self.content_type == ContentType.objects.get_for_model(Apple):
            apple = self.content_object
            return "Apple {} from Farm {}".format(apple, apple.farm)
        elif self.content_type == ContentType.objects.get_for_model(Chocolate):
            chocolate = self.content_object
            return …
Run Code Online (Sandbox Code Playgroud)

django optimization foreign-keys generic-foreign-key

16
推荐指数
1
解决办法
5471
查看次数

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

我有一种情况,其中特定类的大量对象被迭代,并且它们花费大量时间进行处理,因为我不能使用预先选择数据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?

python django

9
推荐指数
1
解决办法
3818
查看次数