Search code examples
pythondjangomodels

How to detect if a file has changed in a model save function


When updating a record with an existing file if the file has changed I need to remove the old file from the S3 bucket.

How in Django can I detect if a file has changed?

This is what I have tried (not tested) but does Django have some magic build in for this?

def save(self, *args, **kwargs):

    existing_file = Asset.objects.get(pk=self.pk)
    if existing_file != self.file:
        # remove from s3 before saving the new file

Solution

  • == and != would only compare primary keys of the model instances (look at the __eq__() and __ne__() methods implementation).

    One way to compare all the fields of the model instances is to call model_to_dict() on both:

    from django.forms.models import model_to_dict
    
    if model_to_dict(existing_file) != model_to_dict(self.file):
    

    You can also specify fields and exclude arguments to control what fields to dump to dictionary, in your case, basically what fields to compare.

    Hope that helps.