how to override the save method of models

1

I'm trying to override the save method of models so that when a new workbook is created it will be saved and exported immediately to a .json file, this would be a form of automatic backup, but when you register a new workbook it exports all the items minus the last one registered, but it should export all, could anyone give me an example of how kindly to override this method correctly ??

def save(self, filename="books", *args, **kwargs):
    get = serializers.serialize("json", Books.objects.all())
    bkp = open("backup/" + filename + ".json", "w")
    bkp.write(get)
    super(Books, self).save(*args, **kwargs)
    
asked by anonymous 21.04.2016 / 00:14

2 answers

1

It is not exporting the last one registered because the save() method inside the model works as pre_save . To resolve this problem you should use the post_save signal.

from django.dispatch import receiver
from django.db.models.signals import post_save

@receiver(post_save, sender=Book)
def faz_backup_de_livros(sender, instance, created, **kwargs):
    filename = instance.filename  # getattr(instance, 'filename', 'backup')
    get = serializers.serialize("json", Books.objects.all())
    bkp = open("backup/" + filename + ".json", "w")
    bkp.write(get)

After you save a workbook, the faz_backup_de_livros method will be called, which will save the backup file.

book = Book()
book.titulo = 'Meu livro'
book.filename = 'meu_livro'
book.save()

You can learn more about signals here: link

    
21.04.2016 / 07:56
0

Orion's answer is very pretty and I fully agree with his solution. However, part of your question is how to properly override the save method of a subclass of Model.

What you do is right, there is nothing wrong with your overriding. However, in order for you to get the last saved book, you must call the parent class method before you can back up:

def save(self, filename="books", *args, **kwargs):
    super(Books, self).save(*args, **kwargs)
    get = serializers.serialize("json", Books.objects.all())
    bkp = open("backup/" + filename + ".json", "w")
    bkp.write(get)

As you wrote, the object is only saved after the backup, so it is incomplete.

Now, man, I need to tell you something, have you ever wondered what will happen to your bank if a lot of people save books at the same time? Also, if the number of data in the database is too large, do not you think the response time for each book creation / update will be too large? What's more, what happens to the file if two books are saved at the same time?

    
21.04.2016 / 19:05