Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - How do I see a primary key id for a newly created record?

How do I see an primary key id for a newly created record?

models.py:

class Foo(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    foobar = db.Column(db.String(64), unique = True)
def __init__(self, foobar):
    self.foobar = foobar

views.py:

foo = Foo(foobar)
db.session.add(foo)
id = How?(foo.id)
like image 674
G33K Avatar asked Nov 03 '25 16:11

G33K


1 Answers

 db.session.flush()
 #id is a Python builtin...
 id_= foo.id

What's happening is that your original code before the flush was in your program only, nothing in db. The id column is likely an auto-generated field that gets assigned at insert time. Once the record is inserted (the flush writes changes to the db), SQLAlchemy basically does a select id from <inserted> and returns the results (various databases use various mechanisms for that). And now you have id populated.

Commits and rollbacks are different in nature from flush. They affect what's already in the db.

Also, flagging your comment I need to use it while adding other records in DB. I explained how to get the id field value, but that doesn't mean it's appropriate to use in your wider context. SQLAlchemy has different ways to link records before flush().

like image 175
JL Peyret Avatar answered Nov 06 '25 06:11

JL Peyret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!