代码之家  ›  专栏  ›  技术社区  ›  pistacchio

SQLAlchemy:插入语句、实际SQL和跳过字段

  •  0
  • pistacchio  · 技术社区  · 8 年前

    我有以下的sqlAlchemy模型:

    class SchemaVersion(Base):
        __tablename__ = 'schema_version'
    
        timestamp = Column(DateTime, default=datetime.datetime.utcnow, primary_key=True)
        version   = Column(String)
        notes     = Column(String)
    

    我能做到的最接近的是:

    statement = insert(SchemaVersion).values(version='v1.0.0',
                                             notes='Initial schema')
    
    print(statement.compile(engine, compile_kwargs={'literal_binds': True}))
    

    engine 是我使用的引擎吗(Postgres)

    生成的打印SQL是:

    INSERT INTO schema_version (timestamp, version, notes) VALUES (%(timestamp)s, 'v1.0.0', 'Initial schema')
    

    问题当然是 %(timestamp)s

    我怎样才能通过 now() 作为值还是让SQLAlchemy为我使用默认值?如果我尝试:

    statement = insert(SchemaVersion).values(timestamp=datetime.datetime.utcnow(),
                                             version='v1.0.0',
                                             notes='Initial schema')
    

    我得到错误:

    NotImplementedError: Don't know how to literal-quote value datetime.datetime(2018, 8, 21, 9, 50, 11, 732957)
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Ilja Everilä    8 年前

    虽然有点不清楚为什么您有兴趣生成带有绑定文本的SQL字符串,但是您可以避免 only simple types such as int and str are supported 在这种情况下,通过在数据库中生成时间戳 CURRENT_TIMESTAMP :

    statement = insert(SchemaVersion).values(timestamp=func.current_timestamp(),
                                             version='v1.0.0',
                                             notes='Initial schema')
    

    这将编译成

    INSERT INTO schema_version (timestamp, version, notes)
    VALUES (CURRENT_TIMESTAMP, 'v1.0.0', 'Initial schema')