Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())
like image 720
jerboa Avatar asked Jul 15 '11 11:07

jerboa


1 Answers

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.
like image 188
Rick Avatar answered Oct 23 '22 06:10

Rick