So, using and learning with sqlalchemy.
I have an instance, I need to get a value. If that value exists, return it.
If not calculate and return it.
Invariably someone will say 'you're doing it wrong' and input on improvement is appreciated in general.
However I am looking into how I can do this without explicitly having to manage the session, because what I'm working on is starting to grow, and constantly managing the session for when I want to update an instance is problematic. It makes me think that I am in fact doing it wrong.
So how do I fix the method below to not have manage the session explicitly?
def method(self, session):
if self.i_needed_this is None:
self.i_needed_this = calculate(calcutron)
Your question is so common, that the answer to it is in the Session Frequently Asked Questions of SA documentation:
session = Session.object_session(someobject)
However, it assumes the object is persistent and is either new (but added to a session already) or bound to a session. Your sample code contains logic to add the object to the session, so my assumption might not be true in this case.