【问题标题】:Django aggregate ForeignKey hierarchyDjango 聚合 ForeignKey 层次结构
【发布时间】:2020-08-25 11:46:26
【问题描述】:

假设我有模型FooBarFooBarBar 具有对 Foo 的 ForeignKey 引用。 FooBar 具有对 Bar 的 ForeignKey 引用。给定一个Foo 对象,我如何最有效地收集所有相关的FooBar 对象?我不喜欢用这个:

foobars = []
for bar in foo.bar_set.all():
    for foobar in bar.foobar_set.all():
        foobars.append(foobar)

【问题讨论】:

  • 你想为一个 foo 获取所有 foobars?

标签: python-3.x django django-aggregation


【解决方案1】:

只需跨越关系就可以了

foobars = FooBar.object.filter(bar__foo=foo)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多