How to avoid model edit in presave Django

I am trying to save in Django model at once this would trigger an event. When updating this model triggering the start_event again and again. How to trigger the event only at first time save not in update?

Image(models.Model):
    file_name = models.CharField(max_length=200)
    file_path = models.CharFiedld(max_length=500)
    def save(self, *args, **kwargs):
        start_event(self.file_path)
        super(Image, self).save(*args, **kwargs)

Using this model first create and update. Create

from models import Image
image = Image()
image.file_path = "path/to/file"
image.save()

After the event completion will use Update

from models import Image
image = Image.objects.get(file_path='path/to/file')
image.file_name = "file/name"
image.save()

How to trigger the event(start_event) only at first time save not in update?

1 answer

  • answered 2018-04-17 06:33 Krish V

    @Zev your info helped it! From the link Django - Overriding the Model.create() method? found the solution.

    def save(self, *args, **kwargs):
        if not self.pk: # Checking if the oject has no pk
            start_event(self.file_path)
        super(Image, self).save(*args, **kwargs)