Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you find out if a Django Model instance is "dirty"?

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.

like image 954
Matthew Schinckel Avatar asked Jul 17 '09 05:07

Matthew Schinckel


2 Answers

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__
like image 156
Matthew Schinckel Avatar answered Sep 18 '22 16:09

Matthew Schinckel


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

like image 24
Vinay Sajip Avatar answered Sep 20 '22 16:09

Vinay Sajip