[Django]-When should we use the advanced parameters of save()?

5👍

The answer is you will know when you need to 🙂
For now resort to this practice

class MyModel(models.Model):

def save(self,*args, **kwargs):
   # do whatever
   super(MyModel,self).save(*args,**kwarags)

This way you make sure that you don’t accidentally drop any of those mysterious, parameters. But let’s try to demystify some of them.

using=self._db

This is to facilitate the use of multible databases in a single django app. Which most apps don’t really need.

update_fields

If save() is passed a list of field names in keyword argument
update_fields, only the fields named in that list will be updated.
This may be desirable if you want to update just one or a few fields
on an object. There will be a slight performance benefit from
preventing all of the model fields from being updated in the database

https://docs.djangoproject.com/en/1.11/ref/models/instances/

So the link to the source code is a specific instance where they have used this feature. Quite useful to keep track of when a user logged in for the last time without updating the entire record.

force_insert vs force_update

These tell django to try forcing one or the other operation. Also explained to some extent in https://docs.djangoproject.com/en/1.11/ref/models/instances/

👤e4c5

1👍

The example of user.save(using=self._db) I believe is redundant when you only have one db, usually defined as “default
. This example simply points out that if you have multiple dbs, you can pass in which of multiple dbs to use when saving.

0👍

update_fields is also handy when you keep a reference to an instance for a long time (for example in a middleware) and the data might be changed from somewhere else. In these cases you either have to perform a costly refresh_from_db() on the instance to get the newest data from the database, or when you only want to override specific attributes you can omit the refresh_from_db() call and just use save(update_fields=['attr1', 'attr2']). This will leave all other attributes unchanged in the database except for the ones you specified. If you omit update_fields in this case all values would be overwritten in the database with the values of your cached reference to the instance, leading to information loss.

👤F.M.F.

Leave a comment