Django的。覆盖模型保存

【字号: 日期:2024-03-07浏览:25作者:雯心
如何解决Django的。覆盖模型保存?

一些想法:

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 = valself._image_changed = True# Or put whole logic in heresmall = 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) # this is not needed if small_image is created at 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)

不确定是否可以在所有伪自动django工具中正常运行(例如:ModelForm,contrib.admin等)。

解决方法

在保存模型之前,我需要重新调整图片大小。但是,如何检查是否添加了新图片或仅更新了说明,以便每次保存模型时都可以跳过重新缩放?

class Model(model.Model): image=models.ImageField(upload_to=’folder’) thumb=models.ImageField(upload_to=’folder’) description=models.CharField() def save(self,*args,**kwargs):if self.image: small=rescale_image(self.image,width=100,height=100) self.image_small=SimpleUploadedFile(name,small_pic)super(Model,self).save(*args,**kwargs)

我只想在加载新图像或更新图像时重新缩放,而在更新说明时不想要。

相关文章: