本文介绍了在Django(SQL,Python,Django)中使用get_or_create()批量插入的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
item_list中的项目:
e,new = Entry .objects.get_or_create(
field1 = item.field1,
field2 = item.field2,
)
解决方案
您无法使用get_or_create(甚至创建)进行体面的插入,并且没有API可以方便地进行。
如果您的表格足够简单,用原始SQL创建行并不是太多的痛苦,这不是太难了;类似于:
INSERT INTO site_entry(field1,field2)
(
SELECT i.field1,i .field2
FROM(VALUES%s)AS i(field1,field2)
LEFT JOIN site_entry as existing
ON(existing.field1 = i.field1 AND existing.field2 = i.field2)
WHERE existing.id IS NULL
)
其中%s是一个字符串像(field1,field2),(field3,field4),(field5,field6)
,你必须自己正确地创建和转义。 / p>
Is there a more efficent way for doing this?
for item in item_list:
e, new = Entry.objects.get_or_create(
field1 = item.field1,
field2 = item.field2,
)
解决方案
You can't do decent bulk insertions with get_or_create (or even create), and there's no API for doing this easily.
If your table is simple enough that creating rows with raw SQL isn't too much of a pain, it's not too hard; something like:
INSERT INTO site_entry (field1, field2)
(
SELECT i.field1, i.field2
FROM (VALUES %s) AS i(field1, field2)
LEFT JOIN site_entry as existing
ON (existing.field1 = i.field1 AND existing.field2 = i.field2)
WHERE existing.id IS NULL
)
where %s is a string like ("field1, field2"), ("field3, field4"), ("field5, field6")
that you'll have to create and escape properly yourself.
这篇关于在Django(SQL,Python,Django)中使用get_or_create()批量插入的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!