Python SQL Alchemy空标识密钥

Python SQL Alchemy空标识密钥,python,mysql,sqlalchemy,flask-sqlalchemy,Python,Mysql,Sqlalchemy,Flask Sqlalchemy,我定义了表的模型id字段,如下所示: id = Column(Integer(15, unsigned=True), nullable=False, server_default='0', primary_key=True, unique=True, autoincrement=True) 并相应地修改了数据库(MySQL)表,但在创建模型时仍然

我定义了表的模型id字段,如下所示:

id = Column(Integer(15, unsigned=True),
               nullable=False,
               server_default='0',
               primary_key=True,
               unique=True,
               autoincrement=True)
并相应地修改了数据库(MySQL)表,但在创建模型时仍然如此 并尝试提交它(我使用SQLalchemy 0.7.8)

我得到这个错误

FlushError: Instance <MyModel at 0x4566990> has a NULL identity key. 
If this is an auto-generated value, check that the database table 
allows generation of new primary key values, and that the mapped 
Column object is configured to expect these generated values.  Ensure 
also that this flush() is not occurring at an inappropriate time, such    
as within a load() event.
FlushError:实例的标识键为空。
如果这是一个自动生成的值,请检查数据库表
允许生成新的主键值,并且
列对象被配置为期望这些生成的值。确保
此外,此flush()不是在不适当的时间发生的,例如
在load()事件中。

我通过删除服务器的默认值解决了这个问题

你能告诉我们你在使用哪个数据库吗,你在使用哪个版本的sqlalchemy,以及结果对你来说什么是重要的(即pks必须从0开始,或者你可以从1开始吗)?我在使用sqlalchemy 0.7.8和MySQLdb。不,零并不重要。我询问正在使用的数据库后端的原因是,您将在sqlite3中遇到此问题,而不是在postgresql中遇到此问题。要完全消除这个问题,只需删除“server_default='0')参数,它就可以在任何一个数据库中工作。我的印象是,虽然sqlite支持自动递增主键,但它无法生成值并在刷新之前返回它们。另一件值得注意的事情是,在默认情况下,设置primary_key=True也会设置autoincrement=True和nullable=False,因此您也可以删除它们。是的,您是对的!它在没有服务器的情况下工作得很好,默认值
unique
unsigned
也不是必需的。这只会让你的代码更复杂。我建议不要在那里设置长度限制,让数据库将id列作为默认整数处理。所以它可以是:
id=Column(Integer,primary\u key=True)
FlushError: Instance <MyModel at 0x4566990> has a NULL identity key. 
If this is an auto-generated value, check that the database table 
allows generation of new primary key values, and that the mapped 
Column object is configured to expect these generated values.  Ensure 
also that this flush() is not occurring at an inappropriate time, such    
as within a load() event.