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.
A solution that does do a database query:
class DirtyMixin(object):
@property
def is_dirty(self):
db_obj = self.__class__.objects.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__
Another way, involving overriding __setattr__
, is discussed at some length in this Django ticket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With