Peewee: How to update certain fields?

I am using Peewee

to work with a database. I have a table User

with three fields: username

, password

and last_login

. When the user logs in, I want to update last_login

. I am using the 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 have not specified any value for password

, it is overwritten upon invocation u.save()

. How do I force peewee to update the field last_login

only?

+3


source to share


3 answers


Replace u.save()

with:

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

      

As the API documentation says :



(list) . List of fields to save - when delivered, only the specified fields are saved.

So, you have to provide the list of fields that you want to change.

+2


source


The following code will show you how to create, get, and update a record in a database:



now = datetime.datetime.now()

# create a user
u = User.create(username="user1", password="bla", last_login=now)
# now `u` has your user, you can do: print u.username, u.password, u.last_login

# get an existing user from the db
u = User.get(User.username == "user1")
print u.username, u.password, u.last_login

sleep(1)
now = datetime.datetime.now()

# update an existing user
u = User.update(password="blabla", last_login=now).where(User.username == "user1")
u.execute()

      

+1


source


You can use an argument only

when calling save()

. http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.save

When the user logs in, I want to update last_login. I am using the following lines of code:

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

User.update({User.last_login: datetime.datetime.now()}).where(User.username == 'whatever').execute()

      

0


source







All Articles