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

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

    If you do not find interest in overriding save method, you can do

      model_fields = [f.name for f in YourModel._meta.get_fields()]
      valid_data = {
            key: new_data[key]
            for key in model_fields
            if key in new_data.keys()
      }
    
      for (key, value) in valid_data.items():
            if getattr(instance, key) != value:
               print ('Data has changed')
    
            setattr(instance, key, value)
    
     instance.save()
    

提交回复
热议问题