
如题,django 中貌似只有 bulk_update 和 bulk_create,有什么办法可以实现 bulk_update_or_create 吗
1 hmxxmh 2019-12-11 10:14:34 +08:00 for 循环 + update_or_create |
3 est 2019-12-11 10:22:41 +08:00 ORM 再厉害也没法实现 sql 支持不了的事。建议直接撸 insert ... on duplicate update ... |
4 wonder1z OP @est ORM 支持 update_or_create 的 只不过没有批量的 bulk_update_or_create。单条撸性能太差了 |
6 hmxxmh 2019-12-11 10:30:43 +08:00 @wonder1z 平时只用 bulk_create,刚才查了一圈,没有看到 bulk_update_or_create。。。数据量有多大? |
7 Ehco1996 2019-12-11 10:40:50 +08:00 @wonder1z bulk_create 的本质其实是 insert many 而你的需求是 update_or_create 貌似单条 sql 是做不到的 ( 我也不确定 我觉得比较简单的是分成两步 然后外面套事务 * bulk_create * bulk_update |
12 hmxxmh 2019-12-11 16:48:26 +08:00 @ytymf with transaction.atomic 只是进入事务,异常统一回滚,不能提升性能,其实我觉得一下创建上千条,肯定慢,放到 celery 里面让他慢慢跑吧 |
13 ytymf 2019-12-11 16:59:57 +08:00 @hmxxmh 你说的没错,这个原意只是保证原子性的事务提交。但在 django 实践中,确实比循环中的每次隐式事务提交快非常多,试试就知道了。 |
14 ytymf 2019-12-11 17:02:34 +08:00 @hmxxmh 具体的原因,猜测是是 model.save 应该会每次建立断开数据库连接,显式事务中 commit 后才断开。没有具体求证过 |
16 encro 2019-12-12 10:47:14 +08:00 |
17 0kaka 2020-03-01 13:24:17 +08:00 create( ) |
18 bnm965321 2020-03-12 10:23:50 +08:00 建议拆分成两个数据集合,先用 unique 字段查询哪些需要 update,然后拆分 |