在我的模型中,我有:
class Alias(MyBaseModel): remote_image = models.URLField(max_length=500, null=True, help_text="A URL that is downloaded and cached for the image. Only used when the alias is made") image = models.ImageField(upload_to='alias', default='alias-default.png', help_text="An image representing the alias") def save(self, *args, **kw): if (not self.image or self.image.name == 'alias-default.png') and self.remote_image : try : data = utils.fetch(self.remote_image) image = StringIO.StringIO(data) image = Image.open(image) buf = StringIO.StringIO() image.save(buf, format='PNG') self.image.save(hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue())) except IOError : pass
第一次remote_image修改效果很好。
remote_image
有人修改remote_image别名上的时,如何获取新图像?其次,是否有更好的方法来缓存远程映像?
本质上,你想覆盖__init__方法,models.Model以便保留原始值的副本。这样一来,你就不必进行其他数据库查找(这总是一件好事)。
__init__
models.Model
class Person(models.Model): name = models.CharField() __original_name = None def __init__(self, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) self.__original_name = self.name def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.name != self.__original_name: # name changed - do something here super(Person, self).save(force_insert, force_update, *args, **kwargs) self.__original_name = self.name