在提交会话之前获取插入的密钥 [英] 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
必须是包含在 child
表中.在我创建 child
对象的那一刻,parent.id
是 None.
I want to INSERT into both parent
and child
tables inside a session considering that the parent_id
must be included in the child
table. In the moment I create the child
object, parent.id
is None.
我怎样才能做到这一点?
How can I achieve that?
推荐答案
你可以使用 flush() 将更改刷新到数据库,从而更新您的主键字段:
You could use flush() to flush changes to the database and thus have your primary-key field updated:
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)
这篇关于在提交会话之前获取插入的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文