在提交会话之前获取插入的密钥

Get inserted key before commit session

class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

parent = Parent()
db.session.add(parent)

child = Child()
child.parent_id = parent.id
db.session.add(child)

db.session.commit()

考虑到parent_id必须被列入childtable。在我创建 child 对象的那一刻,parent.idNone.

我怎样才能做到这一点?

您可以使用 flush() 将更改刷新到数据库,从而更新您的主键字段:

parent = Parent()
db.session.add(parent)
db.session.flush()

print parent.id  # after flush(), parent object would be automatically
                 # assigned with a unique primary key to its id field 

child = Child()
child.parent_id = parent.id
db.session.add(child)