Update only selected model fields
Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day. Django's model.save() method is a PITA: 1. It does a SELECT first to see if the instance is already in the database. 2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed. 3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps. If you just want to update a field or two on a model instance which is already in the database, try this: update_fields(user, email='[email protected]', is_staff=True, last_login=datetime.now()) Or you can add it to your models (see below) and then do this: user.update_fields( email='[email protected]', is_staff=True, last_login=datetime.now()) To add it to your model, put it in a module called granular_update, then write this in your models.py: import granular_update class User(models.Model): email = models.EmailField() is_staff = models.BooleanField() last_login = models.DateTimeField() update_fields = granular_update.update_fields
- fields
- model
- save
- performance
- field
- update
- integrity
- consistency