迭代django对象以更新它们的最有效方法是什么?

str*_*iwi 4 python django django-database

所以我有一个查询集要更新

stories = Story.objects.filter(introtext="")
for story in stories:
    #just set it to the first 'sentence'
    story.introtext = story.content[0:(story.content.find('.'))] + ".</p>" 
    story.save()
Run Code Online (Sandbox Code Playgroud)

而save()操作完全破坏了性能。并且在进程列表中,“ ./ manage.py shell”有多个条目,是的,我通过django shell运行了它。

但是,过去我运行过不需要使用save()的脚本,因为它更改了许多字段。这些脚本非常出色。我的项目有此代码,这可能与为什么这些脚本如此出色有关。

@receiver(signals.m2m_changed, sender=Story.tags.through)
def save_story(sender, instance, action, reverse, model, pk_set, **kwargs):
    instance.save()
Run Code Online (Sandbox Code Playgroud)

有效更新大型查询集(10000+)的最佳方法是什么?

cat*_*ran 5

至于新introtext值取决于content对象的字段,则不能进行任何批量更新。但是您可以通过将单个对象列表包装到事务中来加快保存速度:

from django.db import transaction

with  transaction.atomic():
    stories = Story.objects.filter(introtext='')
    for story in stories:
        introtext = story.content[0:(story.content.find('.'))] + ".</p>" 
        Story.objects.filter(pk=story.pk).update(introtext=introtext)
Run Code Online (Sandbox Code Playgroud)

transaction.atomic() 将以一个数量级增加速度。

filter(pk=story.pk).update()技巧使您可以防止简单情况下发出的任何pre_save/ post_save信号save()。这是官方推荐的更新对象单个字段的方法