2

I'm trying to use SQLAlchemy, but in the line:

session.save(login)

I'm getting this error:

AttributeError: 'Session' object has no attribute 'save'

This is my code:

def findOrCreateLogin(self, username, password):
    login = self.findLogin(username)
    if login:
        return login
    else:
        login = DBLogin(username,password)
        session.save(login)
        return login

2 Answers 2

6

There is no .save() method for an SQLAlchemy session. You can add things to an SQLAlchemy session by:

session.add(login) # Adds a thing to the session.
session.commit() # Commits this session to the database (saves the data).

More information in the session docs

Your code should look like this:

def findOrCreateLogin(self, username, password):
    login = self.findLogin(username)
    if login:
        return login
    else:
        login = DBLogin(username,password)
        session.add(login)
        session.commit()
        return login
Sign up to request clarification or add additional context in comments.

Comments

3

Actually, session.save used to exists in older version of SQLAlchemy.

So if others are looking for a new way of doing insert or update kind of feature - you should use merge:

# if the keys ( primary etc .. ) matching an existing row - it will be updated
# if not - it will be "inserted" as new

new_obj = session.merge(obj)
session.commit()

vs

def findOrCreateLogin() ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.