Efficient way to bulk insert with get_or_create() in Django (SQL, Python, Django)

后端 未结 5 2072
清酒与你
清酒与你 2020-12-14 02:13

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 =         


        
5条回答
  •  遥遥无期
    2020-12-14 02:42

    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.

提交回复
热议问题