在Django中使用get_or_create()进行批量插入的有效方法(SQL,Python,Django) [英] Efficient way to bulk insert with get_or_create() in Django (SQL, Python, Django)

查看:524
本文介绍了在Django中使用get_or_create()进行批量插入的有效方法(SQL,Python,Django)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更有效的方法?

 对于item_list中的项目:
e,新=输入.objects.get_or_create(
field1 = item.field1,
field2 = item.field2,


解决方案

您无法使用get_or_create(甚至无法创建)进行体面的批量插入,并且没有API可以轻松地做到这一点。



如果您的表足够简单,以至于用原始SQL创建行就不会太麻烦,那也就不会太困难。

 插入到site_entry(field1,field2)

SELECT i.field1,i .field2
FROM(VALUES%s)as i(field1,field2)
左联接site_entry作为现有
ON(existing.field1 = i.field1 AND existing.field2 = i.field2)
exist.id是NULL

其中%s是字符串像( field1,field2),( field3,field4),( field5,field6)一样,您必须自己创建和转义。 / p>

Is there a more efficient 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中使用get_or_create()进行批量插入的有效方法(SQL,Python,Django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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