Matt
Matt

Reputation: 1632

SQLAlchemy add vs add_all

I'm trying to figure out when to use session.add and when to use session.add_all with SQLAlchemy.

Specifically, I don't understand the downsides of using add_all. It can do everything that add can do, so why not just always use it? There is no mention of this in the SQLalchemy documentation.

Upvotes: 8

Views: 10142

Answers (3)

timmanna
timmanna

Reputation: 33

As per the implementation of add_all() which is also making an call to add method in a forloop. So even I agree that there no much difference in both. enter image description here

However if you have a requirement of autoincrement and PK/FK relationship then we can't make use of add_all() method in such usecases, but add() method will be handy there.

Upvotes: 0

marcel h
marcel h

Reputation: 788

I was wondering about the same and as mentioned by others, there is no real difference. However, I would like to add that using add in a loop, instead of using add_all allows you to be more fine grained regarding exception handling. Passing a list of mapped class instances to add_all will cause a rollback for all instances if, for example, one of these objects violates a constraint (e.g., unique). I prefer to decouple my data logic from my service logic and decide what to do with instances not stored in the service layer by returning them from my data layer. However, I think it depends on how you are handling exceptions.

Upvotes: 2

Donal
Donal

Reputation: 10150

If you only have one new record to add, then use sqlalchemy.orm.session.Session.add() but if you have multiple records then use sqlalchemy.orm.session.Session.add_all(). There's not really a significant difference, except the API of the first method is for a single instance whereas the second is for multiple instances. Is that a big difference? No. It's just convenience.

Upvotes: 6

Related Questions