[Fixed]-Overridden save() method behavior not using super().save() method

0👍

Thanks everyone for your answers – after careful examination I may safely conclude that I tripped over my own two feet.

After careful examination and even a trip with pdb, I found that the original code had mixed indentation – \t instead of \s{4} before the last super().save().

1👍

If your pk is None, super’s save() is called twice, which I think is not you expect. Try these changes:

class Person(models.Model):
    def save(self, *args, **kwargs):
        is_created = True if not self.pk else False
        super(Person, self).save(*args, **kwargs)
        if is_created and self.some_field == 'Foo': 
            for otherModelInstance in OtherModel.objects.all(): 
                new_Intermediary_Model_instance = IntermediaryModel.objects.create(person = self, other = otherModelInstance)

0👍

It’s not such a good idea to override save() method. Django is doing a lot of stuff behind the scene to make sure that model objects are saved as they expected. If you do it in incorrectly it would yield bizarre behavior and hard to debug.

Please check django signals, it’s convenient way to access your model object information and status. They provide useful parameters like instance, created and updated_fields to fit specially your need to check the object.

Leave a comment