关于Django批量保存对象的问题 [英] Question about batch save objects in Django

查看:25
本文介绍了关于Django批量保存对象的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 的在线文档中没有看到有关此主题的任何内容.

I haven't seen any thing on this topic in Django's online documents.

我正在尝试将对象列表保存到数据库中,但我能做的是遍历列表并在每个对象上调用 save().

I am trying to save a list of objects to database, but what I can do is loop through the list and call save() on every object.

那么 Django 会多次命中数据库吗?或者 Django 会做一次批量保存?

So does Django hit database several times? Or Django will do one batch save instead?

推荐答案

不幸的是,批量插入是 Django 1.3 及之前版本不直接支持的.如果要使用 ORM,则必须对每个单独的对象调用 save().如果它是一个大列表并且性能是一个问题,您可以使用 django.db.cursor 在事务中手动插入项目以显着加快进程.如果您有一个庞大的数据集,则需要开始查看特定于数据库引擎的方法,例如 Postgres 中的 COPY FROM.

Unfortunately, batch inserts are something that Django 1.3 and prior do not directly support. If you want to use the ORM, then you do have to call save() on each individual object. If it's a large list and performance is an issue, you can use django.db.cursor to INSERT the items manually inside a transaction to dramatically speed the process up. If you have a huge dataset, you need to start looking at Database engine specific methods, like COPY FROM in Postgres.

这篇关于关于Django批量保存对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆