Leyo R
Leyo R

Reputation: 723

How to use values like Default and Onupdate in flask-SQLAlchemy

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?

Upvotes: 9

Views: 10432

Answers (1)

davidism
davidism

Reputation: 127200

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.

Upvotes: 25

Related Questions