Search code examples
python-3.xpeewee

peewee save changed fields only


I have this model in peewee:

class User(Model):
    username = CharField()
    password = CharField()
    
    class Meta:
        database = db

I change password and save the model like this:

u = User.get()
u.password = 'newpassword'
u.save()

It update both username and password but i want to update password only.


Solution

  • Enable only_save_dirty meta option and call save() like before, peewee will save dirty fields only.

    Definition:

    class User(Model):
        username = CharField()
        password = CharField()
        
        class Meta:
            database = db
            only_save_dirty = True
    

    Usage:

    u = User.get()
    u.password = 'newpassword'
    u.save()  # username will not updated in DB