Django:保存时,如何检查字段是否已更改? [英] Django: When saving, how can you check if a field has changed?
问题描述
在我的模型中,我有:
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
更改。
Which works great for the first time the remote_image
changes.
如果有人修改了别名的 remote_image
,我如何获取新图像?其次,是否有更好的方法来缓存远程图像?
How can I fetch a new image when someone has modified the remote_image
on the alias? And secondly, is there a better way to cache a remote image?
推荐答案
虽然有点迟了,解决这个问题的其他人。实质上,您要覆盖 __ init __
方法 models.Model
,以便保留原始值的副本。这样做就不用再做一个DB查找(这总是一件好事)。
Though it's a bit late, let me throw out this solution for others that come across this post. Essentially, you want to override the __init__
method of models.Model
so that you keep a copy of the original value. This makes it so that you don't have to do another DB lookup (which is always a good thing).
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
这篇关于Django:保存时,如何检查字段是否已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!