Lucas
Lucas

Reputation: 21

Get primary key from SqlAlchemy before commit the object

I have been using sqlalchemy with postgres and dont know how to solve the issue bellow.

I want to get the value of primary key before commit to DB.

I have a class called process that has proc_id and another element called proc_num.

class process(db.Model):
    __tablename__ = 'tb_processos'
    proc_id = db.Column(db.Integer, primary_key=True, nullable=False,
                        autoincrement=True, unique=True)
    proc_num = db.Column(db.String(20))

For my reasons the proc_num must to be a String type.

When I create my object I want the proc_num receives the proc_id.

How is the best way to do this?

Sorry for my english :/

Thx

Upvotes: 0

Views: 1167

Answers (1)

metmirr
metmirr

Reputation: 4302

You can use flush() method, the changes aren't persisted permanently to disk, until you call commit():

p = process(proc_num=45)
db.session.flush(p)
p = process.query.filter_by(proc_num=45)
p.proc_id

# finally you can call commit
db.session.commit()

Upvotes: 3

Related Questions