Something I don't know how to do in an elegant fashion:

Given a model instance that already exists in the database and is
about to be updated (i.e. some columns of the DB row are changed), is
there a way for the instance's save() method to see what fields have
been changed?

I'm writing an app where a custom change log entry must exist for each
model instance change. Assume this code:

- - - - -

class SomeModelChangeLog(models.Model):
    somemodel = models.ForeignKey('SomeModel')
    message = models.CharField(max_length=255) # maybe a TextField
instead, depends.
    created = models.DateTimeField(default=datetime.datetime.now(),
editable=False)


class SomeModel(models.Model):
    name = models.CharField()
    created = models.DateTimeField(default=datetime.datetime.now(),
editable=False)
    (...etc...)

    def save(self, force_insert=False, force_update=False):
        if self.pk:
            # Somehow find out what fields are about to change, create
a new instance of a change log entry model
            SomeModelChangeLog.objects.create(message="...")
        super(SomeModel, self).save(force_insert, force_update)


sm_foo = SomeModel.objects.create(name="Just some model")
# Do something completely different here, maybe in a completely
different request
# ... time passes ...
sm_bar = SomeModel.objects.get(name="Just some model")
sm_bar.name = "Just some random model"
sm_bar.save()

- - - - -

For the above scenario, I want to construct a change log message that
says something like: "name was changed from 'Just some model' to 'Just
some random model' by [LoggedInUsername]". As the code indicates, this
would happen inside the save() method of SomeModel.

The thing I can't figure out is this: when the object is retrieved as
sm_bar and the 'name' field is changed (but before running save()), is
there any way to "see through" the new 'name' in the instance to
retrieve the old 'name' still in the database? When entering save(),
the in-database values could then be rather trivially compared to the
fresh instance values to construct the change log entry. Of course,
this would have to work for any model with an arbitrary number of
fields and an arbitrary number of field changes.

I have a hunch that 
http://docs.djangoproject.com/en/dev/ref/models/instances/#what-happens-when-you-save
is the way to a solution, but it's not coming to me right now.

Thanks in advance for any help!
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to