Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 602
stefanobaldo Avatar asked Jan 30 '15 18:01

stefanobaldo


1 Answers

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)
like image 93
Paul Lo Avatar answered Nov 15 '22 07:11

Paul Lo