0

所以我想为模板视图获取一些模型对象,但我需要先调用每个选定元素的计算热度或计算排名。

models = Model.objects.a_bunch_of_filtering_sorting()

那么有什么快速的方法来做到这一点呢?
也许重申名单?

for model in models: # Surely it can't be this
   model.the_method()

我尝试做一些自定义 SQL 的东西,但它不允许任何方法调用或列表排序太早

sortValue = ORDER BY ....
cursor = connection.cursor()
cursor.execute("""
SELECT d.field1, d.field2 ........ 
# unfortunately method calls aren't allowed in here

FROM Model_model d
GROUP BY 1
%s""" % sortValue)

for row in cursor.fetchall():
d = self.model(id=row[0] .... )
d.the_method() # wont work, the list is already 
               # ordered so we are calculating a sorting key one step behind

那么在对所有 django 模型(最首选的方式)进行排序并将它们发布到模板之前,我可以采取哪些可能的步骤来调用方法

谢谢

4

2 回答 2

1

这个

for model in models:
   model.the_method()

你可以试试这个

from itertools import imap
from collections import deque
from operator import methodcaller
deque(imap(methodcaller('the_method'), models), maxlen=0)

但它通常不会更快/更快,当然也不会更清晰

于 2012-09-24T05:59:18.940 回答
0

如果方法the_method执行新的 SQL,并且模型的数量很大,那么它真的会损害性能,因为每个对象都有额外的查询。在这种情况下,最好只执行一条 SQL 来更新所有需要的对象。如果the_method不执行新查询,则使用循环非常好 - 它们正是为此目的而制作的。

于 2012-09-24T10:03:03.443 回答