5

How to get ids from bulk inserting in Peewee?

I need to return inserted ids for create a new array of dict like this:

a = [{"product_id": "inserted_id_1", "name": "name1"}, {"product_id": "inserted_id_2", "name": "name1"}]

Then I need to insert this using bulk like:

ids = query.insertBulk(a)

In its turn the last query should return me new ids for further similar insertion.

  • I believe there is no way around this calling `create()` but only with `atomic()` context manager http://docs.peewee-orm.com/en/latest/peewee/querying.html#bulk-inserts – vishes_shell Feb 18 '18 at 21:06

1 Answers1

4

If you're using Postgresql, which supports queries of the form "INSERT ... RETURNING", you can get all the IDs:

data = [{'product_id': 'foo', 'name': 'name1'}, {...}, ...]
id_list = SomeModel.insert_many(data).execute()

For SQLite or MySQL, which do not support the RETURNING clause, you're probably best off doing this:

with db.atomic() as txn:
    accum = []
    for row in data:
        accum.append(SomeModel.insert(row).execute())
coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Will I take returned ids in `accum` array? –  Feb 19 '18 at 15:37
  • If you're using SQLite or MySQL and have the requirement that you collect the IDs of all inserted rows, what else you gonna do? – coleifer Feb 19 '18 at 19:05