13

Should I use () with datetime.now in defining tables? What code wrong 1 or 2?

1:

Base = declarative_base()
class T(Base):
    __tablename__ = 't'

    created = Column(DateTime, default=datetime.now)

2:

Base = declarative_base()
class T(Base):
    __tablename__ = 't'

    created = Column(DateTime, default=datetime.now())

1 Answer 1

20

You want the first case. What you're doing is telling SqlAlchemy than whenever a row is inserted, run this function (callable) to get the default value. That can be any callable function or a string value.

This way the function is called exactly at insert time and you get the correct date that it was inserted.

If you use the second value, you'll find that all of the default values share the same datetime. That will be the value that occurred the first time the code was processed.

http://www.sqlalchemy.org/docs/core/schema.html?highlight=default#sqlalchemy.schema.ColumnDefault

This could correspond to a constant, a callable function, or a SQL clause.
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.