Django的。覆盖模型的保存在保存模型之前,我会重新调整图片大小。但是,如何检查是否添加了新图片或更新了描述,以便每次保存模型时都可以跳过重新缩放?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)我想仅在新图像加载或图像更新时重新缩放,但在更新描述时不重新缩放。
3 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
一些想法:
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) # 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等)。
添加回答
举报
0/150
提交
取消