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


Question

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,
    )
1
21
9/7/2017 2:29:58 PM

Accepted Answer

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.

10
2/12/2010 7:13:53 PM

Depends on what you are aiming at. You can use manage.py's loaddata function to load data in a appropriate format (JSON, XML, YAML,...).

See also this discussion.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon