Home  >  Article  >  Backend Development  >  How to Override Django Model\'s Save Method for Selective Image Resizing?

How to Override Django Model\'s Save Method for Selective Image Resizing?

DDD
DDDOriginal
2024-10-22 16:26:02174browse

How to Override Django Model's Save Method for Selective Image Resizing?

Overriding Django Model's Save Method for Selective Resizing

Question:

How can Django model's save method be overridden to resize an image only when it is added or updated, but not when other fields are edited?

Problem:

The provided code resizes an image every time the model is saved, even if only the description is updated. This is inefficient and unnecessary.

Solution:

The suggested solution involves creating a property that serves as a setter and getter for the image field. This allows tracking changes to the image field and only resizing when it is modified:

<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

        # 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)</code>

By using this approach, resizing only occurs when the image is added or updated, effectively addressing the concern raised in the original question.

The above is the detailed content of How to Override Django Model\'s Save Method for Selective Image Resizing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn