When saving, how can you check if a field has changed?

前端 未结 25 1841
鱼传尺愫
鱼传尺愫 2020-11-22 07:15

In my model I have :

class Alias(MyBaseModel):
    remote_image = models.URLField(max_length=500, null=True, help_text=\"A URL that is downloaded and cached          


        
25条回答
  •  悲&欢浪女
    2020-11-22 07:30

    Since Django 1.8 released, you can use from_db classmethod to cache old value of remote_image. Then in save method you can compare old and new value of field to check if the value has changed.

    @classmethod
    def from_db(cls, db, field_names, values):
        new = super(Alias, cls).from_db(db, field_names, values)
        # cache value went from the base
        new._loaded_remote_image = values[field_names.index('remote_image')]
        return new
    
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if (self._state.adding and self.remote_image) or \
            (not self._state.adding and self._loaded_remote_image != self.remote_image):
            # If it is first save and there is no cached remote_image but there is new one, 
            # or the value of remote_image has changed - do your stuff!
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题