-3

I am creating models, where i get bit confusion about save() has another save method with super keyword, why two save() methods, appreciate for explination.

    from django.db import models

    class Blog(models.Model):
        name = models.CharField(max_length=100)
        tagline = models.TextField()

        def save(self, *args, **kwargs):
            do_something()
            super().save(*args, **kwargs)  # Call the "real" save() method.
            do_something_else()
Saisiva A
  • 595
  • 6
  • 24
  • 2
    Does this answer your question? [What does 'super' do in Python?](https://stackoverflow.com/questions/222877/what-does-super-do-in-python) – JPG Mar 04 '20 at 09:45
  • Read [this](https://realpython.com/inheritance-composition-python/) for example as a good introduction in python object-oriented programming and class inheritance. – dirkgroten Mar 04 '20 at 09:46
  • i have knowledge in super method, why its calling two save() methods. – Saisiva A Mar 04 '20 at 09:47
  • What do you think `super()` does exactly? Why exactly is `super().save()` confusing to you? – deceze Mar 04 '20 at 09:52

1 Answers1

1

The save method which actually does all the database work is defined in models.Model.save. Your Blog class is overriding the save method; when you call Blog().save(), it just executes whatever is in your Blog.save method. That wouldn't do any of the actual work of writing to the database.

To do something of your devising in your Blog.save method and also run all the code defined in models.Model.save, you need to explicitly call the parent's save implementation. Which is what super().save() does.

deceze
  • 510,633
  • 85
  • 743
  • 889