Django Find difference in the same model instance

I've been searching around and I don't think I've found my answer quite yet. But I'm looking to be able to find differences in data and have a list of column names that show that.

Take for instance I have a model just called my_model that has some columns.

object = my_model.objects.get(id=1)

# Perform edit some values.

old_object = my_model.objects.get(id=1)

object.save()

# Check for differences
model_fields = [field.name for field in my_model._meta.get_fields()]

filtered_list = filter(lambda field: getattr(object, field, None) != getattr(old_object, field, None), model_fields)

Purpose of this is to notify the user after they make an update on their end to send an email to that user to just give them a reminder that they changed whatever values they changed.

Was able to answer my own question. Converting the two objects to dictionaries. I was able to end up with something like

dict1, dict2 = obj1.__dict__, obj2._dict__

changed_fields = {
    'column_names': []
}

excluded_keys = '_state'

for k,v in dict1.items():
    if k in excluded_keys:
        continue
    try:
        if v != dict2[k]
        changed_fields['column_names'].append(k)
    except KeyError:
    # Put error handling
        continue
Back to Top