Django: Difference Between Two Model Instances

April 29th, 2008  |  Published in Django, Web Development

Just a quick snippet, I call this code on a site I’m working on to handle some basic moderation. It finds the difference between the two instances, and returns a dictionary of the changes. The key in the dictionary is the field name, each value in the dictionary is a tuple containing the new and old value of the field.

You can pass it the excludes field to exclude certain fields from being compared. It does not compare AutoField or RelatedField’s.

1
2
3
4
5
6
7
8
9
10
from django.db.models import fields
def get_changes_between_models(model1, model2, excludes = []):
    changes = {}
    for field in model1._meta.fields:
        if not (isinstance(field, (fields.AutoField, fields.related.RelatedField)) 
                or field.name in excludes):
            if field.value_from_object(model1) != field.value_from_object(model2):
                changes[field.verbose_name] = (field.value_from_object(model1),
                                                   field.value_from_object(model2))
    return changes

Based off of code from Django Modelhistory.

Leave a Response

Subscribe via RSS

If you like the content of this website and are looking for a way to be notified of new content, look no further. Just click the orange icon to your right and subscribe using your favorite feed reader.