django - comparing old and new field value before saving

前端 未结 8 736
温柔的废话
温柔的废话 2020-12-12 20:40

I have a django model, and I need to compare old and new values of field BEFORE saving.

I\'ve tried the save() inheritence, and pre_save signal. It was triggered cor

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 20:50

    Django 1.8+ and above (Including Django 2.x and 3.x), there is a from_db classmethod, which can be used to customize model instance creation when loading from the database.

    Note: There is NO additional database query if you use this method.

    Here is the link to the official docs Model instance - Customize model loading

    from django.db import Model
    
    class MyClass(models.Model):
        
        @classmethod
        def from_db(cls, db, field_names, values):
            instance = super().from_db(db, field_names, values)
            
            # save original values, when model is loaded from database,
            # in a separate attribute on the model
            instance._loaded_values = dict(zip(field_names, values))
            
            return instance
    

    So now the original values are available in the _loaded_values attribute on the model. You can access this attribute inside your save method to check if some value is being updated.

    class MyClass(models.Model):
        field_1 = models.CharField(max_length=1)
    
        @classmethod
        def from_db(cls, db, field_names, values):
            ...
            # use code from above
    
        def save(self, *args, **kwargs):
    
            # check if a new db row is being added
            # When this happens the `_loaded_values` attribute will not be available
            if not self._state.adding:
    
                # check if field_1 is being updated
                if self._loaded_values['field_1'] != self.field_1:
                    # do something
    
            super().save(*args, **kwargs)
                
                
    

提交回复
热议问题