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

时间:2015-01-30 18:37:39

标签: python flask sqlalchemy flask-sqlalchemy

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()

我希望 INSERT 进入会话中的parentchild表,考虑到parent_id必须包含在child表中。在我创建child对象的那一刻,parent.id

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:30)

您可以使用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)