My Code,
class User(db.Model, UserMixin):
uid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(250), unique=True)
password = db.Column(db.String(250))
name = db.Column(db.String(250))
created_on = db.Column(db.TIMESTAMP, default=False)
modified_on = db.Column(db.TIMESTAMP, onupdate=datetime.datetime.now)
I want to create a field timestamp, which will have a default value timestamp and onupdate will change again to the current timestamp. But when I run the migrations, this does not create the field in MySQL with default or onupdate values, what am i doing wrong?
There is a difference between SQLAlchemy's defaults and SQL defaults. Typically, setting the SQLAlchemy defaults should be enough, as you should not be interacting directly with the server normally. If you really want to render defaults on the server side, use the server_default
and server_onupdate
arguments to Column
.
db.Column(
db.DateTime, nullable=False,
server_default=db.func.current_timestamp(),
server_onupdate=db.func.current_timestamp()
)
Personally, I don't like this solution because it moves behavior from your application to a separate location, where you might overlook it later. It simpler to just do the defaults on the Python side:
db.Column(
db.DateTime, nullable=False,
default=datetime.utcnow,
onupdate=datetime.utcnow
)
Also, consider changing from using datetime.now
to datetime.utcnow
, as UTC is much easier to work with behind the scenes. Only ever convert to localtime when displaying something to a user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With