sqlalchemy没有设置timestmap默认值

时间:2015-07-22 15:06:07

标签: python mysql datetime sqlalchemy

SQLAlchemy并不尊重default=datetime.datetime.utcnowdefault=func.now()DateTime(我已尝试过两者)。

的Python:

class DataStuff(BASE): 
    """some data""" 
    __tablename__ = 'datastuff' 
    _id = Column(Integer, primary_key=True) 
    _name = Column(String(64)) 
    json = Column(sqlalchemy.UnicodeText()) 
    _timestamp = Column(DateTime, default=datetime.datetime.utcnow) 

MySQL的:

mysql> describe datastuff;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| _id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| _name         | varchar(64)  | YES  |     | NULL    |                |
| json          | text         | YES  |     | NULL    |                |
| _timestamp    | datetime     | YES  |     | NULL    |                |

1 个答案:

答案 0 :(得分:0)

根据使用server_default的文档,当期望的操作是在CREATE TABLE语句中的列上提供默认值时,可以采用这种方法。

http://docs.sqlalchemy.org/en/rel_1_0/core/defaults.html

我最终使用server_default功能而不是func.now()使用default=datetime.datetime.utcnow

新代码:

from sqlalchemy import func
_timestamp = Column(DateTime, server_default=func.now()) 

<强>结果:

+---------------+--------------+------+-----+-------------------+----------------+
| Field         | Type         | Null | Key | Default           | Extra          |
+---------------+--------------+------+-----+-------------------+----------------+
| _timestamp    | datetime     | YES  |     | CURRENT_TIMESTAMP |                |

中提琴