Sometimes, we want to override save for model with Python Django.
In this article, we’ll look at how to override save for model with Python Django.
How to override save for model with Python Django?
To override save for model with Python Django, we add our own save method to the model class.
For instance, we write
class Model(model.Model):
_image=models.ImageField(upload_to='folder')
thumb=models.ImageField(upload_to='folder')
description=models.CharField()
def set_image(self, val):
self._image = val
self._image_changed = True
# Or put whole logic in here
small = rescale_image(self.image,width=100,height=100)
self.image_small=SimpleUploadedFile(name,small_pic)
def get_image(self):
return self._image
image = property(get_image, set_image)
def save(self, *args, **kwargs):
if getattr(self, '_image_changed', True):
small=rescale_image(self.image,width=100,height=100)
self.image_small=SimpleUploadedFile(name,small_pic)
super(Model, self).save(*args, **kwargs)
to add the save method into the Model class.
In it, we call rescale_image to rescale an image,
Then we create a SimpleUploadedFile object from the image.
And then we call save to save the Model instance with the parent class’ save method.
Conclusion
To override save for model with Python Django, we add our own save method to the model class.