Django: Overriding save method for specific model scenarios
In situations where the save method of a Django model needs to be modified based on certain criteria, such as determining if an image was updated or only the description changed, a custom approach can be employed.
One technique involves using a property and a flag:
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
def get_image(self):
return self._image
image = property(get_image, set_image)
def save(self, *args, **kwargs):
if getattr(self, '_image_changed', True):
# Logic for image rescaling
super(Model, self).save(*args, **kwargs)
This approach ensures that the image rescaling logic is only triggered when the '_image_changed' flag is set to True, indicating that the image has been modified.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3