Django — Detect what fields have been changed / modified on save.

How to detect which fields have been changed upon saving a model.

I just needed a quick way to detect which fields have been changed as a convenience for a team.

This is what I came up with.

Is it too expensive to do comparisons like this?

Please let me know if you have any suggestions.


    def __init__(self, *args, **kwargs):
        super(Order, self).__init__(*args, **kwargs)
        self._initial_data = self.__dict__.copy()

    def detect_changed(self, user='System'):
        changed = [k for k, v in self._initial_data.iteritems() \
                        if v != self.__dict__[k] and k not in ('log','activity','_state',)]
        if changed:
            self._activity("%s changed %s" % (user.first_name, str(changed).replace('[','').replace(']','') ) )

One thought on “Django — Detect what fields have been changed / modified on save.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s