Django: Prefetch相关的多个反向关系



我有以下模型:

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")

但是当我循环test_params_data并打印每个实例的__dict__时,我只在_prefetched_objects_cache参数中获得carnivore_set

那么如何在prefetch_related中获得多级反向关系呢?

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

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

最新更新