Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-peewee get last saved row

Tags:

python

orm

peewee

is there a way how to obtain last saved row in database while using peewee with all its attributes? Let's say I do this:

user = User.create(
    email = request.json['email'],
    nickname = request.json['nickname'],
    password = request.json['password'],
    salt = "salt"
)

But user.id is None and the only attributes I can get are those specified above. I could call select() method but isn't there there any faster way?

Thanks

like image 726
skornos Avatar asked Jul 10 '14 11:07

skornos


3 Answers

User.select().order_by(User.id.desc()).get()

This will get the last-created user assuming the IDs is an auto-incrementing integer (the default).

Or if you want to get e.g. last created customer (user), you can write it like this:

User.select().where(User.type == "customer").order_by(User.id.desc()).get()

If you want to get the last saved user, you need to add a timestamp to indicate when the user is saved.


Update:

Peewee also now supports RETURNING clause for Postgres database. You can add a RETURNING clause to any INSERT, UPDATE or DELETE query. Check out the docs:

  • http://docs.peewee-orm.com/en/latest/peewee/querying.html#returning-clause
  • http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=returning#InsertQuery.returning
like image 193
coleifer Avatar answered Nov 03 '22 01:11

coleifer


Instead of re-querying the DB, one alternative is the following:

u = User(email="..", nickname="..", password="..", salt="..")
u.save()

# at this point, peewee inserted the entry in the DB,
# and updated all relevant fields (including the ID).
# For example, you can do the following:

print "ID of last-created user: %d" % u.id

For complex, multi-threaded systems, I think this a better alternative.

like image 22
reyammer Avatar answered Nov 03 '22 02:11

reyammer


I'm guessing your User model looks like this:

class User(Model):
    id = IntegerField(primary_key=True)
    email = TextField(unique=True)
    nickname = TextField()
    password = TextField()
    salt = TextField()

But peewee doesn't know how to handle autoincrementing fields unless you use its PrimaryKeyField class:

class User(Model):
    id = PrimaryKeyField()
    email = TextField(unique=True)
    nickname = TextField()
    password = TextField()
    salt = TextField()

This wasn't documented anywhere I could find. Source.

like image 44
jtschoonhoven Avatar answered Nov 03 '22 01:11

jtschoonhoven