【问题标题】:Django - nested relation query with the ORMDjango - 使用 ORM 的嵌套关系查询
【发布时间】:2018-12-01 07:30:08
【问题描述】:

因为我需要避免递归导入并使用 Group 对象作为我查询的起点(这就是为什么我不能直接导入 Action 对象。)

关系是Group -> Component -> ComponentVersion -> Action

例如,Group.components.all() 返回查询集中的所有组件。

另外[component.versions.all() for component in Group.components.all()] 返回一个查询集列表,其结果是所有版本。随后,.actions.all() 将为理解中返回的每个 ComponentVersion 返回 actions 的所有查询集。

避免对数据库进行不必要的调用和提高可读性的最佳方法是什么?

【问题讨论】:

    标签: django orm django-queryset django-related-manager


    【解决方案1】:

    Prefetch Related 从这里开始,这将运行 4 个查询,但会立即检索所有数据,而不是迭代和进行多个查询。

    Group.objects.all().prefetch_related('components', 'components__versions', 'components__versions__actions')
    

    【讨论】:

    • 抱歉我的误解,但我如何访问实际的actions 对象?我有你提到的东西component_qs = Group.components.all().prefetch_related('versions', 'versions__actions'),所以我可以做[component for component in component_qs],它会按预期返回一个组件列表。如果我例如尝试[component.versions.actions for component in component_qs] 我得到RelatedManager object has no attribute actions
    • 是的,因为版本是相关的管理器,而不是您需要一次获得一个版本操作的操作。 Component.versions()[0].actions。或者以任何方式获取版本,您可能需要嵌套列表推导,但此时可能有更直接的方法。
    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 2016-09-28
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多