Django: Before a model is updated, I'd like to “look at” its previous attributes

后端 未结 5 709
星月不相逢
星月不相逢 2021-02-13 16:36

When an update/create is performed on a Django model (.save()) I would like to be able to \"step in\" and compare some particular attributes to what they were set t

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 17:07

    You can use the pre_save signal and compare the db record (the old version) with the instance record (the updated, but not saved in the db version).

    Take a model like this one as example:

    class Person(models.Model):
        Name = models.CharField(max_length=200)
    

    In a pre_save function you can compare the instance version with the db version.

    def check_person_before_saving(sender, **kwargs):
        person_instance = kwargs['instance']
        if person_instance.id:
            # you are saving a Person that is already on the db
            # now you can get the db old version of Person before the updating
    
            # you should wrap this code on a try/except (just in case)
            person_db = Person.objects.get(id=person_instance.id)
    
            # do your compares between person_db and person_instance
            ...
    
    # connect the signal to the function. You can use a decorator if you prefer
    pre_save.connect(check_person_before_saving, sender=Person)
    

提交回复
热议问题