appleLover
appleLover

Reputation: 15691

SQLAlchemy Commit Changes

Inside of the declarative base I define a function like this:

def update_me(self):
   if self.raw_info==1: self.changed_info=10
   else: self.changed_info=20

I know this can be done with hybrid_property but I actually do more complicated manipulations, the above is just for illustrative purposes, this has to be done through a method. How can I commit these changes, from inside the declarative base, without passing it the session object? It seems logical that there would be a way, if I can access the object and change its values without a session object, then it seems like I should be able to save it here somehow. Of course adding this code to the end of the function above fails

self.commit()

Upvotes: 1

Views: 709

Answers (1)

javex
javex

Reputation: 7544

It seems to me that you might want to reconsider your design. However, if you are sure you want to go this way, you can use the object_session method:

object_session(self).commit()

Warning: This will commit your whole session (not just one object) and it will only work if self is already attached to a session (by Session.add or having queried for it, for example). Thus, it will be a fragile operation and I would not recommend it unless absolutely necessary.

But you are right, when you say

It seems logical that there would be a way, if I can access the object and change its values without a session object, then it seems like I should be able to save it here somehow.

The object and the session are connected and thus changes will be delivered to the database. We get this connected session with the method above.

Upvotes: 1

Related Questions