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

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

    The optimal solution is probably one that does not include an additional database read operation prior to saving the model instance, nor any further django-library. This is why laffuste's solutions is preferable. In the context of an admin site, one can simply override the save_model-method, and invoke the form's has_changed method there, just as in Sion's answer above. You arrive at something like this, drawing on Sion's example setting but using changed_data to get every possible change:

    class ModelAdmin(admin.ModelAdmin):
       fields=['name','mode']
       def save_model(self, request, obj, form, change):
         form.changed_data #output could be ['name']
         #do somethin the changed name value...
         #call the super method
         super(self,ModelAdmin).save_model(request, obj, form, change)
    
    • Override save_model:

    https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model

    • Built-in changed_data-method for a Field:

    https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.changed_data

提交回复
热议问题