how to override save method of models

Asked

Viewed 915 times

1

I am trying to overwrite the save method of models so that when a new book is created it is saved and exported immediately to a file. json, this would be a form of automatic backup, but when registering a new book it exports all the items except the last one registered, but it should export all, someone could give me an example of how to overwrite 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)
  • This method is within some class?

  • Yes, this is in my model class, the save function referenced above and used to override the pattern used by models.Model.

2 answers

1


It is not exporting the last registered because the method save() inside the model works as pre_save. To solve this problem you must use Signal post_save.

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 book, you will be called the method faz_backup_de_livros 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: https://docs.djangoproject.com/es/1.9/ref/signals/#post-save

0

Orion’s response is very beautiful and I fully agree with his solution. However, part of your doubt is how to properly override the save method of a Model subclass.

What you do is right, there’s nothing wrong with your envelope. Only, for you to get the last book saved, you must call the parent class method before backup:

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)

The way you wrote, the object is only saved after backup, so it gets incomplete.

Now, man, I need to tell you something, you ever think about what’s gonna 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, don’t 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?

  • Hello @Pablo, thank you for your return, yes, I totally agree with your way of thinking, a lot could happen, however, the data that will be inserted in the data bunch, are a bit important, I thought to use this backup medium as security, in case something happens with the database I will have the same saved in an external file, and since you put these points on the agenda, by chance you would not have a more viable (advisable) way to work with backup not?

  • @dhelbegor, there are several ways to do this, varying from situation to situation. Because of this, there is a lot of written material (give a search by backup, Recovery and database replication), because, believe me, other people also have important data. Possible solutions would be to replicate the data on another server and, as well, create a service to hold dumps every x time.

  • @dhelbegor this backup method that you are implementing is not good, the right one would be to backup the database. In case you just want to backup book registration, could program to save this file json once a day and not every time something is registered or edited. Remember that your code is not taking into account that a book can be deleted, I think you should update the backup after a delete too.

  • Yes, I am in total agreement @Orion, this was just a test that I thought to implement, but I knew the risks that the same could bring, I am seeing some things about standalone and other options of the same branch, I already appreciate the help of all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.