简体   繁体   English

在Django中加速批量ORM操作的策略

[英]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). 我的一个API调用可能导致对大量对象(Django模型)的更新。 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',...)". 有时我的过滤条件看起来像“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. 您需要手动使用事务或创建sql语句。 You could also try using SQLAlchemy which supports a few great ORM features like Unit of Work (or application transaction). 您还可以尝试使用SQLAlchemy,它支持一些很棒的ORM功能,如工作单元(或应用程序事务)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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