Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peewee : How to update specific fields?

I'm using Peewee for working with database. I have a User tables with 3 fields: username, password and last_login. When a user login to the system i want to update last_login. I've use following lines of code:

from peewee import *
import datetime

class User(Model):
    username = CharField(unique=True)
    password = CharField()
    last_login = DateTimeField(default=datetime.datetime.now())

    class Meta:
        database = MySQLDatabase('mydb', user='root', charset='123456')


u=User(username="user1", last_login=datetime.datetime.now())
u.save()

Although i haven't specified any value for password, it is overwritten after u.save() is called. How should i force peewee to only update last_login field?

like image 395
Reza Fallahpour Avatar asked Jan 30 '23 23:01

Reza Fallahpour


2 Answers

Replace u.save() with:

u.save(only=[User.last_login])

As the API's documentation says:

only (list) – A list of fields to persist – when supplied, only the given fields will be persisted.

So you should specify a list of fields you want to be changed.

like image 164
SuB Avatar answered Feb 05 '23 18:02

SuB


You can use the only argument when calling save(). http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.save

When a user login to the system i want to update last_login. I've use following lines of code:

If you want to do this, you should do an atomic update, however:

User.update({User.last_login: datetime.datetime.now()}).where(User.username == 'whatever').execute()
like image 34
coleifer Avatar answered Feb 05 '23 16:02

coleifer