django-model-changes icon indicating copy to clipboard operation
django-model-changes copied to clipboard

Related object in creation action

Open emigue opened this issue 7 years ago • 0 comments

Related objects does not appear in previous_changes() method after object creation. For example, if your model has an "creator" field that references to auth.User and you set creator during creation, previous_changes() method does not show 'creator': [null, user].

To fix this problem, you could include next code in _save_state method:

    def _save_state(self, new_instance=False, event_type='save'):

        if new_instance and not self.pk:  # new instance
            self._states.append(self.new_state())
        else:
            # Pipe the pk on deletes so that a correct snapshot of the current
            # state can be taken.
            if event_type == DELETE:
                self.pk = None
            # Save current state.
            self._states.append(self.current_state())
        ...

And add the new function too:

    def new_state(self):
        """
        Returns a ``field -> None`` dict of the initial state of the instance.
        """
        field_names = set()
        [field_names.add(f.name) for f in self._meta.local_fields]
        [field_names.add(f.attname) for f in self._meta.local_fields]
        return dict([(field_name, None) for field_name in field_names])

If you are ok with that, I can make a PR to the library.

emigue avatar Aug 18 '17 11:08 emigue