Check the value of the previous model when saving

I have a model that saves Excursion. The user can change this excursion, but I need to know what the excursion is before they change it because I keep track of how many "bookings" are made per excursion, and if you change your excursion, I need to remove one reservation from the previous excursion.

I'm not really sure how this should be done.

I assume you are using a signal for this?

Should I use pre_save, pre_init or what would be better for this?

pre_save is not correct as it prints the new values ​​and not the "old value" as I expected

@receiver(pre_save, sender=Delegate)
def my_callback(sender, instance, *args, **kwargs):
    print instance.excursion

      

+3


source to share


2 answers


You have several options.

The first is to overwrite the save method :

#Delegate
def save(self, *args, **kwargs):
    if self.pk:
        previous_excursion = Delegate.objects.get(self.pk).excursion
    super(Model, self).save(*args, **kwargs)
    if self.pk and self.excursion != previous_excursion:
        #change booking

      

Second binding function to send save message + django model utils field tracker :



@receiver(post_save, sender=Delegate)
def create_change_booking(sender,instance, signal, created, **kwargs):
    if created:
        previous_excursion = get it from django model utils field tracker
        #change booking

      

And another solution is found in pre_save as it starts up:

@receiver(pre_save, sender=Delegate)
def my_callback(sender, instance, *args, **kwargs):
    previous_excursion = Delegate.objects.get(self.pk).excursion
    if instance.pk and instance.excursion != previous_excursion:
        #change booking  

      

+7


source


Alternatively and if you are using Django forms:

The current version of your instance is stored in form.instance

your model's Django forms. On save, checks are performed and this new version is applied to the model, and then the model is saved.

This means you can check the differences between the new and old versions by comparing form.instance

with the current model.

This is what happens when the Django Admin method is called save_model

. (See tab /admin/options.py)



If you can use Django forms, this is the most Djangothic way to go, I would say.

This is the gist of using a Django form to handle data changes:

form = ModelForm(request.POST, request.FILES, instance=obj)
new_object = form.instance  # not saved yet
# changes are stored in form.changed_data
new_saved_object = form.save()

      

form.changed_data

will contain the changed fields, which means it is empty if there is no change.

+1


source







All Articles