使用一个大的INSERT语句保存许多Django对象 [英] Saving many Django objects with one big INSERT statement
问题描述
想象一下,您有以下情况:
Imagine you have the following situation:
for i in xrange(100000):
account = Account()
account.foo = i
account.save
显然,100,000 Django执行的语句 INSERT 将需要一些时间。将所有这些 INSERT
s组合成一个大的 INSERT
将会更好一些。这是我希望我可以做的事情:
Obviously, the 100,000 INSERT
statements executed by Django are going to take some time. It would be nicer to be able to combine all those INSERT
s into one big INSERT
. Here's the kind of thing I'm hoping I can do:
inserts = []
for i in xrange(100000):
account = Account()
account.foo = i
inserts.append(account.insert_sql)
sql = 'INSERT INTO whatever... ' + ', '.join(inserts)
有没有办法使用QuerySet,而无需手动生成所有这些 INSERT
语句?
Is there a way to do this using QuerySet, without manually generating all those INSERT
statements?
推荐答案
你可以使用原始SQL。
You could use raw SQL.
通过 Account.objects.raw()
或使用django.db.connection对象。
Either by Account.objects.raw()
or using a django.db.connection objects.
如果您想维护数据库不可知性,这可能不是一个选项。
This might not be an option if you want to maintain database agnosticism.
http://docs.djangoproject.com/en/dev/topics/db/sql/
如果你正在做的是一次性设置,也许使用夹具会更好。
If what you're doing is a one time setup, perhaps using a fixture would be better.
这篇关于使用一个大的INSERT语句保存许多Django对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!