views:

225

answers:

2

I really like the feature of SQLAlchemy that allows you to see if an object is dirty: if it has been modified since it was retrieved from the database, or the last time it was saved.

Is it possible to find this information from the Django ORM?

Note this is not the same as Dirty fields in django, as I don't care about what the previous data was, although S.Lott's answer may provide a way to do it, but I would like a way that doesn't hit the database.

I have also looked at the django.db.transaction.is_dirty(), but this doesn't seem to be the solution.

+1  A: 

A solution that does do a database query:

class DirtyMixin(object):
@property
def is_dirty(self):
    db_obj = self.get(self.pk)
    for f in self._meta.local_fields:
        if self.__getattribute__(f.name) != db_obj.__getattribute__(f.name):
            return True
    return False

You can then add this as an ancestor class to a model. Or, monkey-patch the forms.Model class, if you like.

from django.db import models
models.Model.__bases__ = (DirtyMixin,) + models.Model.__bases__
Matthew Schinckel
+1  A: 

Another way, involving overriding __setattr__, is discussed at some length in this Django ticket.

Vinay Sajip