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

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?


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)