Get inserted key before commit session

≡放荡痞女 提交于 2019-12-17 07:24:28

问题


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

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?


回答1:


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)


来源:https://stackoverflow.com/questions/28242523/get-inserted-key-before-commit-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!