简体   繁体   中英

Strategies for speeding up batch ORM operations in Django

One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next:

for item in Something.objects.filter(x='y'):
    item.a="something"
    item.save()

Sometimes my filter criterion looks like "where x in ('a','b','c',...)".

It seems the official answer to this is "won't fix" . I'm wondering what strategies people are using to improve performance in these scenarios.

您链接的票证用于批量创建 - 如果您不依赖于重写的save方法或前/后保存信号来执行保存工作, QuerySet有一个update方法 ,您可以使用它来执行UPDATE过滤行:

Something.objects.filter(x__in=['a', 'b', 'c']).update(a='something')

You need to use transactions or create the sql statement by hand. You could also try using SQLAlchemy which supports a few great ORM features like Unit of Work (or application transaction).

Django transactions: http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs

SQLAlchemy: http://www.sqlalchemy.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM