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

Linda Hamilton
Release: 2024-10-22 16:34:03
Original
942 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!