[Answer]-How can I know which values were changed in Django's Model.save() method?

0👍

You will have to fetch it from the DB before the saving:

def save(self, *args, **kwargs):    
    if self.pk is None:
        # Insert query on the external database.
    else:
        old = Lab.objects.get(pk=self.pk)
        if self.name is not old.name:
            ...             

    super(Lab, self).save(*args, **kwargs)

1👍

If you’re using ModelForm for the job, override save method on it and decide whether to cascade to model’s save (call super with commit=True) or not.

You probably have all the information at this point. Now you need a way to use it.

Forms in django have tools for what you need. Check out changed_data attribute and has_changed() method of the form.

class MyModelForm(forms.ModelForm):

    class Meta:
        model = MyModel

    def save(commit=True):
        if self.has_changed():
            super(MyModelForm, self).save(commit=commit)

0👍

so you want to get your data from the database, and you don’t want to make many queries. If your data is not too much, you can just read all the data from your database to the memory, and then compare your about-to-save value with the data in memory, if they are not the same, just assign that value to the memory data as well as updating in the database.

Leave a comment