pythonpython-3.xpeeweeflask-peewee

How to get ids from bulk inserting in Peewee?


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.


Solution

  • 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())