2011-07-15 20 views
13

我應該在datetime.now中使用()定義表嗎?什麼代碼錯誤1或2?日期時間定義數據庫使用sqlalchemy

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

回答

20

你想尚屬首例。你所做的是告訴SqlAlchemy,比插入行時,運行這個函數(可調用)來獲得默認值。這可以是任何可調用函數或字符串值。

通過這種方式,函數在插入時恰好被調用,並且您得到插入的正確日期。

如果使用第二個值,則會發現所有默認值共享相同的日期時間。這將是第一次處理代碼時發生的值。

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. 
相關問題