python - Django 的 objects.all() 杀死 python

标签 python django

我有一个 Django 项目。 models.py 中有MyModel。该模型有 4 000 000 个实例。

我执行这个脚本:

for m in MyModel.objects.all():
    if len(m.phone) < 10 or len(set(m.phone)) <= 2:
        m.delete()

但是,它会杀死 python(只打印“Killed”)。

我知道,问题出在实例数量上。 但是我怎样才能迭代所有这些呢?

最佳答案

您可以尝试先对对象进行计数,然后使用切片版本对它们进行迭代。像这样的东西:

step = 10
count = MyModel.objects.count()/step
for i in xrange(count):
    for m in MyModel.objects.all()[i*step:(i+1)*step]:
        # doing something with m

关于python - Django 的 objects.all() 杀死 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12253328/

相关文章:

python - 突然在运行测试时我得到 "TypeError: ' NoneType' object is not iterable

Django db 备份 postgres 错误

python - 为什么 defaultdict(int) 的 dicts 使用这么多内存? (以及其他简单的 python 性能问题)

python - interpolate.splev 错误 : 'Lengths of the first three arguments (x,y,w) must be equal'

python - 防止 f 字符串将 float 转换为科学记数法

javascript - 将多个 JavaScript 文件组合并压缩到 Django 项目中的单个文件中

python - 匹配 EmbeddedDocumentList 中的 EmbeddedDocument

Django 模型 ForeignKey on_delete 属性 : full meaning?

python - 使用 matplotlib 绘制感知器算法

python - 你如何在 Python 中为一个类型起别名?