jerboa
jerboa

Reputation: 1421

datetime in defining database using sqlalchemy

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())

Upvotes: 13

Views: 6668

Answers (1)

Rick
Rick

Reputation: 16224

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.

Upvotes: 20

Related Questions