我已经在sqlalchemy
(v1.1.10)中创建了一个带有表的数据库,如下所示:
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, MetaData, String, Table
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.automap import automap_base
# Create connection
engine = create_engine("sqlite://", echo=False)
base = declarative_base(engine)
Session = sessionmaker(bind=engine)
session = Session()
meta = MetaData(engine)
# Define table table column names
columns = ['col1', 'col2', 'col3', 'col4']
# Create a table with the appropriate Columns
anomalies = Table('boolean_cols', meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('name', String, nullable=False),
Column('date', DateTime, nullable=False, default=datetime.now()),
*[Column(name, Boolean, nullable=False, default=False) for name in columns])
# Implement it
meta.create_all()
然后我像这样使用automap_base
为表创建一个ORM:
# Generate Base class and add methods
Base = automap_base()
Base.prepare(engine, reflect=True)
# Automap Bools class from Base class
Bools = Base.classes.boolean_cols
这一切似乎都奏效。但是当我尝试将记录添加到表中时...
session.add(Bools(name='foo1', col2=True))
session.commit()
...它说我没有明确列为参数的列的NOT NULL约束失败:
IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: boolean_cols.date [SQL: 'INSERT INTO boolean_cols (name, date, col1, col2, col3, col4) VALUES (?, ?, ?, ?, ?, ?)'] [parameters: ('foo1', None, None, 1, None, None)]
但是创建表时,我在所有这些列上都设置了默认值!知道为什么在尝试将记录插入表时未应用默认值吗?
我可以在nullable=True
参数中设置Column
,但是这对于为date
列自动生成的时间戳没有帮助。此外,该解决方法无法解决未应用默认值的问题!任何帮助将不胜感激。
谢谢!