python - 在 django 中对列表的每个元素调用方法的快速策略是什么

标签 python mysql django postgresql

所以我想为模板 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/

相关文章:

MySQL 只能与 --skip-grant-tables 一起使用,并且无法摆脱它。 Linux

c# - 无法在 asp.net 中连接托管提供商 MYSQL 数据库

python - Django 中的 URLField() 可以加载本地主机路径吗?

django - 无法从主机访问 VMWare guest Web 服务器

python - 如何使用pymongo获取Json文档的所有键?

python - Seaborn FacetGrid 上的 Pandas 图

php - 如何在 foreach 语句中添加值 (PHP)

python - 如何识别django中urls.py文件中以anchor(#)开头的url?

python - 训练速度较慢的简单 DQN

python - 可以在 numpy 中形成 ndarray 对角线的 View 吗