0
votes

I am trying to insert a list of dictionaries into a table using bulk_save_objects or bulk_insert_mappings. Is there any way I can get the list of objects with primary key for each entry?

try:
    cycle_object_list = []
    for cycle in cycle_list:
        period = Period()
        for k, v in cycle.items():
            setattr(period, k, v)
        cycle_object_list.append(period)

    db.session.bulk_save_objects(cycle_object_list)
    db.session.commit()
    print(cycle_object_list)
except Exception:
    db.session.rollback()
    raise
finally:
    db.session.close()

I am expecting something like [Period.49, Period.50, Period.51]

But the actual result is [Period.None, Period.None, Period.None]

1

1 Answers

1
votes

The docs

The objects as given are not added to the session and no additional state is established on them, unless the return_defaults flag is also set, in which case primary key attributes and server-side default values will be populated.

So this might work:

try:
    cycle_object_list = []
    for cycle in cycle_list:
        period = Period()
        for k, v in cycle.items():
            setattr(period, k, v)
        cycle_object_list.append(period)

    db.session.bulk_save_objects(cycle_object_list, return_defaults=True)
    db.session.commit()
    print(cycle_object_list)
except Exception:
    db.session.rollback()
    raise
finally:
    db.session.close()