【发布时间】:2021-11-28 06:38:28
【问题描述】:
我有以下型号:
class Animal(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
class Carnivore(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
animal = models.ForeignKey(Animal)
testing_params = models.ForeignKey(TestParams, blank=True, null=True)
class TestParams(models.Model):
params_1 = models.CharField(max_length=256, blank=True, null=True)
params_2 = models.CharField(max_length=256, blank=True, null=True)
class Metrics(models.Model):
carnivore = models.ForeignKey(Carnivore, null=True, blank=True)
现在我想为TestParams过滤器对象预取carnivoreanimal、metrics。所以我正在做以下事情:
test_params = TestParams.objects.filter(**filters)
test_params_data = test_params.prefetch_related("carnivore_set", "carnivore_set__animal", "carnivore_set__metrics_set")
但是当我遍历test_params_data 并打印每个实例的__dict__ 时,我只会在_prefetched_objects_cache 参数中得到carnivore_set。
那么如何在prefetch_related 中获得多级反向关系?
【问题讨论】:
-
这是有道理的,因为例如
carnivore_set_animal的Prefetch是预取carnivore_set的预取,而不是TestParamss。因此,这是一个“嵌套”预取。
标签: python django django-models django-orm