首页 > 解决方案 > Django:预取相关的多个反向关系

问题描述

我有以下型号:

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)

现在我想为过滤carnivore animal器对象预取。所以我正在做以下事情:metricsTestParams

test_params = TestParams.objects.filter(**filters)

test_params_data = test_params.prefetch_related("carnivore_set", "carnivore_set__animal", "carnivore_set__metrics_set")

但是当我循环并打印每个实例carnivore_set的._prefetched_objects_cachetest_params_data__dict__

那么我怎样才能获得多层次的反向关系prefetch_related呢?

标签: pythondjangodjango-modelsdjango-orm

解决方案


根据@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")            
        )

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


推荐阅读