Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5869

Django : difference between calling self.model.save() and self.model.save(*args,**kwargs)

Is there a difference between calling a model's save like :

self.model.save(*args,**kwargs)

and:

self.model.save()

Upvotes: 0

Views: 832

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

The obvious difference is that in the first case you are passing positional and keyword arguments. If you wonder what arguments Model.save() takes and what they do, the simplest thing is to read the source code. Then you'll find something like:

def save(self, force_insert=False, force_update=False, using=None):
    """
    Saves the current instance. Override this in a subclass if you want to
    control the saving process.

    The 'force_insert' and 'force_update' parameters can be used to insist
    that the "save" must be an SQL insert or update (or equivalent for
    non-SQL backends), respectively. Normally, they should not be set.
    """
    if force_insert and force_update:
        raise ValueError("Cannot force both insert and updating in model saving.")
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)

The third argument, using, is not documented, it specifies which db connection you want to use (if you have more than one db connection).

To make a long story short:

  • when you want to save your instance (in a view or form or whatever), you usually just want to let Django handle all this so you call my_model_instance.save() without arguments
  • when you override the save method in your Model class, you definitly want to accept and pass the same arguments when calling on the base class save, ie:

    class MyModel(models.Model): def save(self, *args, **kw): do_something_here() super(MyModel, self).save(*args, **kw) do_something_else()

Upvotes: 2

Related Questions