Identify the changed fields in django post_save signal

前端 未结 7 1442
再見小時候
再見小時候 2020-12-02 15:28

I\'m using django\'s post_save signal to execute some statements after saving the model.

class Mode(models.Model):
    name = models.CharField(max_length=5)
         


        
相关标签:
7条回答
  • 2020-12-02 16:10

    This is an old question but I've come across this situation recently and I accomplished it by doing the following:

        class Mode(models.Model):
        
            def save(self, *args, **kwargs):
                if self.pk:
                    # If self.pk is not None then it's an update.
                    cls = self.__class__
                    old = cls.objects.get(pk=self.pk)
                    # This will get the current model state since super().save() isn't called yet.
                    new = self  # This gets the newly instantiated Mode object with the new values.
                    changed_fields = []
                    for field in cls._meta.get_fields():
                        field_name = field.name
                        try:
                            if getattr(old, field_name) != getattr(new, field_name):
                                changed_fields.append(field_name)
                        except Exception as ex:  # Catch field does not exist exception
                            pass
                    kwargs['update_fields'] = changed_fields
                super().save(*args, **kwargs)
    

    This is more effective since it catches all updates/saves from apps and django-admin.

    0 讨论(0)
提交回复
热议问题