Reputation: 425
I have a model:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
created_time = db.Column(db.TIMESTAMP, nullable=False)
However, every time I updated name
or password
, the timestamp created_time
would be updated, but I don't want created_time
to be updated.
# the way I update a user's info
class UserController(Resource):
def get(self):
user = User.query.filter_by(id=1).first() # a user had been created before
user.name = "new_name"
db.session.commit()
# as of here, not only `name` but also `created_time` will be update
How to stop created_time
from auto-updating when updating a row?
To be more precise, I would like to know about the mechanism of db.TIMESTAMP
, and more specifically, to resolve the issue that when I update other columns in a row db.TIMESTAMP
column is also updated.
I would instead want the value in db.TIMESTAMP
column to be fixed at the time the row is created, and that value should never change regardless of how values in other columns change.
P.S. To avoid misunderstanding, I know TIMESTAMP
may not be the most appropriate type for created_time
column, but the above code is only for illustrating purposes.
Upvotes: 2
Views: 2463
Reputation: 51
Well, from what I understand, the on_update event trigger which causes your problem is not the default, and it should not be generated without being told explicitly.
see more: Marking Implicitly Generated Values, timestamps, and Triggered Columns
The Ideal way to create created/modified timestamps is like this
class Base():
id = db.Column(db.Integer, primary_key=True)
created_time = db.Column(db.DateTime, server_default=db.func.now())
modified_time = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
src: Define Output Column In Flask-Sqlalchemy
here I found good references which may help you solve the problem. How to stop SQLAlchemy from adding an ON UPDATE clause to a TIMESTAMP column by default
Upvotes: 2