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
, metrics
для TestParams
объектов фильтра. Поэтому я делаю следующее:
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_cache
только когда я перебираю test_params_data
и печатаю __dict__
каждый экземпляр.
Как я могу получить многоуровневые обратные отношения в 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")
)
Это решение сработало для меня. Пожалуйста, не стесняйтесь опубликовать любое лучшее решение, если оно существует.