Filipe Ferminiano
Filipe Ferminiano

Reputation: 8791

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

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

Upvotes: 2

Views: 6493

Answers (2)

Ricky Levi
Ricky Levi

Reputation: 7987

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() ...

Upvotes: 3

msvalkon
msvalkon

Reputation: 12077

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

Upvotes: 6

Related Questions