簡體   English   中英

Django:Prefetch Related multiple reverse relationships

[英]Django: Prefetch Related multiple reverse relationships

我有以下型號:

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)

現在我想預取carnivoreanimal TestParams器對象的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中獲得多級反向關系呢?

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

這個解決方案對我有用。 如果存在任何更好的解決方案,請隨時發布。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM