django - comparing old and new field value before saving

前端 未结 8 723
温柔的废话
温柔的废话 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 21:09

    Here is an app that gives you access to previous and current value of a field right before model will be saved: django-smartfields

    Here is how this problem can be solved in a nice declarative may:

    from django.db import models
    from smartfields import fields, processors
    from smartfields.dependencies import Dependency
    
    class ConditionalProcessor(processors.BaseProcessor):
    
        def process(self, value, stashed_value=None, **kwargs):
            if value != stashed_value:
                # do any necessary modifications to new value
                value = ... 
            return value
    
    class MyModel(models.Model):
        my_field = fields.CharField(max_length=10, dependencies=[
            Dependency(processor=ConditionalProcessor())
        ])
    

    Moreover, this processor will be invoked, only in case that field's value was replaced

    0 讨论(0)
  • 2020-12-12 21:10

    I agree with Sahil that it is better and easier to do this with ModelForm. However, you would customize the ModelForm's clean method and perform validation there. In my case, I wanted to prevent updates to a model's instance if a field on the model is set.

    My code looked like this:

    from django.forms import ModelForm
    
    class ExampleForm(ModelForm):
        def clean(self):
            cleaned_data = super(ExampleForm, self).clean()
            if self.instance.field:
                raise Exception
            return cleaned_data
    
    0 讨论(0)
提交回复
热议问题