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

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

    Best way is with a pre_save signal. May not have been an option back in '09 when this question was asked and answered, but anyone seeing this today should do it this way:

    @receiver(pre_save, sender=MyModel)
    def do_something_if_changed(sender, instance, **kwargs):
        try:
            obj = sender.objects.get(pk=instance.pk)
        except sender.DoesNotExist:
            pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
        else:
            if not obj.some_field == instance.some_field: # Field has changed
                # do something
    

提交回复
热议问题