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