【问题标题】:Django: Prefetch Related multiple reverse relationshipsDjango:预取相关的多个反向关系
【发布时间】: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过滤器对象预取carnivoreanimalmetrics。所以我正在做以下事情:

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_animalPrefetch 是预取carnivore_set 的预取,而不是TestParamss。因此,这是一个“嵌套”预取。

标签: python django django-models django-orm


【解决方案1】:

根据@Willem Van Onsem 的评论,我找到了答案。这是我实施的解决方案:

test_params_data = test_params.prefetch_related(
            Prefetch("carnivore_set", queryset=Carnivore.objects.prefetch_related(
                Prefetch("animal_set", to_attr="animals"),
                Prefetch("metrics_set", to_attr="metrics")), 
            to_attr="carnivores")            
        )

这个解决方案对我有用。如果有更好的解决方案,请随时发布。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-27
    • 2018-07-05
    • 2019-05-18
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    相关资源
    最近更新 更多