2

我已经像这样定义了表的模型的 id 字段:

id = Column(Integer(15, unsigned=True),
               nullable=False,
               server_default='0',
               primary_key=True,
               unique=True,
               autoincrement=True)

并相应地更改了数据库(MySQL)表,但是当我创建模型并尝试提交它时(我使用 SQLalchemy 0.7.8)

m = MyModel(values without defining the id)
session.add(m)
session.commit()

我收到这个错误

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.
4

2 回答 2

1

我使用 Postgres 13,ID 的类型是 UUIT 数据类型。我遇到了同样的问题。我已经通过应用 server_default 解决了这个问题。

class TrafficLightController(Base):
    __tablename__ = 'Tlc'
    id = Column(UUID, primary_key=True, server_default='uuid_generate_v4()')
    type_id = Column('type_id', UUID)
    title = Column('title', String(100))
    gps_x = Column('gps_x', Float)
    gps_y = Column('gps_y', Float)
    hardware_config = Column('hardware_config', JSONB)
    lcu_id = Column('lcu_id', UUID)
    signal_id = Column('signal_id', UUID)

    def __init__(self, type_id, title, gps_x, gps_y, hardware_config, lcu_id, signal_id):
        self.type_id = type_id
        self.title = title
        self.gps_x = gps_x
        self.gps_y = gps_y
        self.hardware_config = hardware_config
        self.lcu_id = lcu_id
        self.signal_id = signal_id

if __name__ == "__main__":
    dbschema = 'asudd'
    engine = create_engine(DB_CONNECTION_STR, connect_args={'options': '-    csearch_path={}'.format(dbschema)})
    Session = sessionmaker(bind=engine)
    Base = declarative_base()
    Base.metadata.create_all(engine)

    session = Session()
    tlc_obj = TrafficLightController("b0322313-0995-40ac-889c-c65702e1841e", "test DK", 35, 45, "{}", None, None)
    session.add(tlc_obj)
于 2021-09-16T06:41:36.023 回答
0

我通过删除 server_default 值解决了它

于 2012-10-23T14:15:06.417 回答