Pav Sidhu Pav Sidhu - 1 month ago 13x
Python Question

SQLAlchemy table property takes exactly 2 arguments (1 given)

I have the following SQLAlchemy class:

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
password = db.Column(db.String(100))

def encrypt_password(self, password):
self.password = hash_password(password)

When I use the property I get the error
encrypt_password() takes exactly 2 arguments (1 given)

user = db.session.query(User).filter_by(id=id).one()

Why doesn't this work? How do I implement a property for setting the password?


You defined the getter for the property as the setter. Either remove the property because this is a function, or define the property correctly.

If you're going the property route, rename the password attribute and access it through the property for the getter. Use a hybrid_property so that the column is still queryable directly.

from sqlalchemy.ext.hybrid import hybrid_property

_password = db.Column('password', db.String)

def password(self):
    return self._password

def password(self, value):
    self._password = hash_password(value)
user.password = 'stack overflow'  # gets hashed
user.password  # hashed value
session.query(User).filter(User.password.is_(None))  # query for users without passwords