Home >Backend Development >Python Tutorial >How to Override Django\'s Save Method for Selective Model Updating?
Django Override Save for Model Only in Some Cases
Problem:
When saving a Django model, you need to resize an image if a new image is added. However, you want to skip resizing if only the model's description is updated.
Solution:
To achieve this, you can create a custom property that acts as a setter for the image field and a flag to indicate whether the image has changed.
<code class="python">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): small = rescale_image(self.image, width=100, height=100) self.image_small = SimpleUploadedFile(name, small_pic) super(Model, self).save(*args, **kwargs)</code>
This solution ensures that the image is resized only when it is changed, while avoiding resizing when only the description is updated. Additionally, this approach maintains compatibility with Django's pseudo-auto tools like ModelForm and contrib.admin.
The above is the detailed content of How to Override Django\'s Save Method for Selective Model Updating?. For more information, please follow other related articles on the PHP Chinese website!