Sqlalchemy模型创建时间避弹坑

创建的模型

from back.database import Base
from sqlalchemy import String, Integer, DateTime, Boolean, Column
from datetime import datetime
class User(Base):
    __tablename__ = 'user'
    ID = Column(Integer, primary_key=True, autoincrement=True)
    Name = Column(String(30), nullable=False)
    Code = Column(String(30), nullable=False, unique=True)
    Age = Column(Integer, default=18)
    PassWord = Column(String(200), nullable=False)
    CreateTime = Column(DateTime, default=datetime.now())
  • 上面代码中CreateTime字段默认值为获取当前时间

  • 启动程序后,调用接口测试,code分别是string1 、string2
    image

  • 查看数据库表中的数据,发现创建时间都是一样的,不论间隔多久调用接口。貌似就是程序跑起来后获取到的当前时间,显然不符合实际的需求
    image

改造

from back.database import Base
from sqlalchemy import String, Integer, DateTime, Boolean, Column, func
from datetime import datetime

# 用户表
class User(Base):
    __tablename__ = 'user'
    ID = Column(Integer, primary_key=True, autoincrement=True)
    Name = Column(String(30), nullable=False)
    Code = Column(String(30), nullable=False, unique=True)
    Age = Column(Integer, default=18)
    PassWord = Column(String(200), nullable=False)
    CreateTime = Column(DateTime, default=func.now())#重点只改了这里

sqlalchemy.fun.now源码

class now(GenericFunction):
    """The SQL now() datetime function.

    SQLAlchemy dialects will usually render this particular function
    in a backend-specific way, such as rendering it as ``CURRENT_TIMESTAMP``.

    """

    type = sqltypes.DateTime
    inherit_cache = True

至此每次调用接口后,创建时间就是实时获取的当前时间了

posted @ 2022-09-04 18:16  弩哥++  阅读(99)  评论(0编辑  收藏  举报