所以我想为模板 View 获取一些模型对象,但我需要先对每个选定元素调用计算热度或计算排名。
models = Model.objects.a_bunch_of_filtering_sorting()
那么什么是快速执行此操作的方法?
也许重申一下这个 list ?
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 模型上的方法(最优选的方式)
谢谢
最佳答案
这个
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)
但通常不会更快,而且肯定不会更清晰
关于python - 在 django 中对列表的每个元素调用方法的快速策略是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12558945/