[Solved]-Passing an argument to a custom save() method


Keyword arguments must follow the positional arguments. Try this instead:

def save(self, my_value, *args, **kwargs):


def save(self, *args, **kwargs):
    my_value = kwargs.pop('my_value', None)


You can try the following.

Override the save method as:

def save(self, my_val, *args, **kwargs):
    print my_val
    # do_something here
    return super(MyModel, self).save(*args, **kwargs)

On calling the save method as:


this will print my_val and save it.


The existing answers are incomplete.

The problem with Model.save is that there are multiple ways to get to it, most notably through Model.objects.create(). A queryset create() call will not pass additional arguments to Model.save and your code might not behave as expected.

You can easily see the source code for create() and other methods (get_or_create, update_or_create) here: https://github.com/django/django/blob/2.2.7/django/db/models/query.py#L415

The bulk_create method of QuerySet does not call save at all. Which means any custom logic will be entirely ignored.

Because of these risks I would consider the premise of the question an anti-pattern to be avoided. Rather than overloading the built in save method, create an entirely different (factory) method to encompass your special behavior e.g. mymodel.special_save().

Leave a comment