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

前端 未结 25 1796
鱼传尺愫
鱼传尺愫 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:22

    Here is another way of doing it.

    class Parameter(models.Model):
    
        def __init__(self, *args, **kwargs):
            super(Parameter, self).__init__(*args, **kwargs)
            self.__original_value = self.value
    
        def clean(self,*args,**kwargs):
            if self.__original_value == self.value:
                print("igual")
            else:
                print("distinto")
    
        def save(self,*args,**kwargs):
            self.full_clean()
            return super(Parameter, self).save(*args, **kwargs)
            self.__original_value = self.value
    
        key = models.CharField(max_length=24, db_index=True, unique=True)
        value = models.CharField(max_length=128)
    

    As per documentation: validating objects

    "The second step full_clean() performs is to call Model.clean(). This method should be overridden to perform custom validation on your model. This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:"

提交回复
热议问题