Search code examples
pythonmysqlpeewee

Get last insert ID in peewee ORM (python)


I would like to retrieve the last insert ID (for use in a second table as a relation), however, I do not know how to get it. I am using the peewee ORM.

The table 'readings' in the database 'nest' has a column 'id' (int (11) auto_increment, primary key).

import time
from peewee import *

database = MySQLDatabase('nest', **{'user': 'nest'})

class Readings(BaseModel):
time = DateTimeField()

class Meta:
    db_table = 'readings'

dt = Readings.insert(time=time.strftime("%x %X"))
dt.execute();
print "Last insert id:", dt.last_insert_id(database, Readings);

The last line is where I am stuck. Thanks a lot for your help.


Solution

  • Thank you very much for the the help, the answer was really easy. Here is the correct code:

    import time
    from peewee import *
    
    database = MySQLDatabase('nest', **{'user': 'nest'})
    
    class Readings(BaseModel):
        time = DateTimeField()
    
    class Meta:
        db_table = 'readings'
    
    dt = Readings.insert(time=time.strftime("%x %X"))
    print "Last insert id: %i" % dt.execute()