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

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

    And now for direct answer: one way to check if the value for the field has changed is to fetch original data from database before saving instance. Consider this example:

    class MyModel(models.Model):
        f1 = models.CharField(max_length=1)
    
        def save(self, *args, **kw):
            if self.pk is not None:
                orig = MyModel.objects.get(pk=self.pk)
                if orig.f1 != self.f1:
                    print 'f1 changed'
            super(MyModel, self).save(*args, **kw)
    

    The same thing applies when working with a form. You can detect it at the clean or save method of a ModelForm:

    class MyModelForm(forms.ModelForm):
    
        def clean(self):
            cleaned_data = super(ProjectForm, self).clean()
            #if self.has_changed():  # new instance or existing updated (form has data to save)
            if self.instance.pk is not None:  # new instance only
                if self.instance.f1 != cleaned_data['f1']:
                    print 'f1 changed'
            return cleaned_data
    
        class Meta:
            model = MyModel
            exclude = []
    

提交回复
热议问题