9

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?

1 Answer 1

25

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.