更新时间:2022-12-12 11:29:55
在Python中创建模型对象时,该对象尚未刷新到数据库。如果是串行列,则数据库负责生成新值,因此生成前只是 None
。在语句中
When you create a model object in Python it is not yet flushed to the DB. In case of a serial column the DB is responsible for generating the new value, and so it is just None
before generation. In the statement
table2 = Table2(table2id=table1.table1id)
您只需阅读 None
并将其作为关键字参数 table2id 传递即可。为了获得一个值,您需要刷新更改到数据库,因此您应该对操作进行一些重新排序:
you simply read that None
and pass it as the keyword argument table2id. In order to obtain a value you need to flush the changes to the database, so you should reorder your operations a bit:
table1 = Table1(name='abc')
session.add(table1)
# Flush the changes to the DB
session.flush()
table2 = Table2(table2id=table1.table1id)
session.add(table2)
session.commit()
SQLAlchemy还可以为您执行大多数操作,或者如果要在表1和表1之间定义关系 2,或者如果这实际上是继承体系。
SQLAlchemy could also perform most of this for you more or less automatically, if you'd define the relationships between table 1 and 2, or if this is actually an inheritance hierarchy.