python - 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
器对象预取。所以我正在做以下事情: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")
)
这个解决方案对我有用。如果存在,请随时发布任何更好的解决方案。
推荐阅读
- regex - 正则表达式从字符串中查找第一个和最后一个日期:输出 12/31/2018 和 12/1/2018
- r - 在列表中汇总结果
- css - 在 Material UI 中将变量发送到 withStyles?
- javascript - 使用 javascript 和正则表达式添加对电话号码输入扩展的支持
- javascript - AJAX POST 中的随机数组值
- python - 带有请求库的 Azure Databricks Python 多处理 API 调用?
- javascript - Express 路由器接收索引页的 GET /index.html.var
- sbt - Sbt Uber Jar 组装MergeStrategy
- ios - Google ios 注册移动到 MainTabBarController
- django - 如何强制 AppEngine 柔性环境中的 Python 3 Django 应用程序始终使用 https?