Django:准备查询但不执行它

时间:2016-12-02 12:05:56

标签: django

我正在尝试在以下循环中使用Django进行一些有效的查询:

for division in divisions:
  playoffs = league.playoff_set.filter(division=division, double_elimination=True)

我认为可能在循环之前过滤playoffs只选择那些double_elimination=True的人会增强它:

playoffs = league.playoff_set.filter(double_elimination=True)
for division in divisions:
  division_playoffs = playoffs.filter(division=division)

但现在我担心这会在循环的每次运行中从playoffs触发查询,而不是过滤先前检索的结果。

它是按预期工作还是我担心?我应该使用Q来构建效果更好的查询吗?

1 个答案:

答案 0 :(得分:4)

Django querysets are lazy。这意味着当您执行

时,不会评估查询集
playoffs = league.playoff_set.filter(double_elimination=True)

在循环中再次过滤查询集时,甚至无法评估。

division_playoffs = playoffs.filter(division=division)
当您访问其内容时(在视图或模板中)

The queryset will only be evaluated

playoffs = league.playoff_set.filter(double_elimination=True)
for division in divisions:
    division_playoffs = playoffs.filter(division=division)
    for playoff in division_playoffs:  # looping through queryset causes it to be evaluated
        print(playoff)

因此,您的代码的两个版本都将起作用。你应该选择你认为更清楚的那个。