如何使用Django管理命令进行多处理?

我有一个可以运行的Django管理命令:“ python manage.py updateprices”并执行以下查询:

activos = SearchTag.objects.filter(is_active=True)

我想将这样的命令拆分成较小的数据库块 e.g. activos[0:2000]同时进行,所以我加快了过程

我该怎么做?

haidimingzhushiwo 回答:如何使用Django管理命令进行多处理?

如果我理解正确,我认为您是在谈论按组进行数据库查询。

因此,首先,您应该创建一个列表(可迭代)

q_list = []
active_q = SearchTag.objects.filter(is_active=True)
# start from 0 and make jumps of 2,000. so if you have 20,000 rows you would have a list containing 10 querysets of 2000 rows each
for i in range(0,active_q.count(),2000):
    q_list.append(active_q[i:i+2000])

现在,您有了要对其进行操作的项目列表,可以轻松地将其传递给池

from multiprocessing import cpu_count,Pool
pool = Pool(processes=cpu_count())
pool.map(function_on_each_q,q_list)

显然,您需要创建该函数以执行所需的操作:

def function_on_each_q(q_list):
    # DO WHATEVER WITH q_list
本文链接:https://www.f2er.com/3138755.html

大家都在问