1

I'm trying to make an assertion inside one of my tests that the fields from a model have not changed. I know that philosophically this is incorrect, but since i control all the variables i need to know about, i just want to check that my DB entry hasn't changed.

I am willing to accept a solution that can transform this into an assertion that some API wasn't called, which is supposed to update models, but i am aware that the API might not be fully documented, so i'd prefer it there was a way to just check if all the field values are equal.

Anyway, i know how to do this, but i'm using django 1.6 and the Model._meta API isn't public yet:

def assertFieldsEqual(self, instance1, instance2)
    for field_name in MyModel._meta.get_all_field_names():
        val1 = getattr(instance1, field_name)
        if not isinstance(val1, django.db.models.Field):
            continue  # this excludes managers
        if val1 != getattr(instance2, field_name):
            return False  # or raise assertion error, or whatever
    return True  # or don't do nothing, or whatever

So is there a better way?

[EDIT] python 2.7

vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124

1 Answers1

2

You can use the django.forms.models.model_to_dict method and compare the resulting dictionaries with a simple dict1 == dict2.

knbk
  • 52,111
  • 9
  • 124
  • 122
  • Although your solution is totally awesome and answered my question, if i wanted to know which are the fields that differ, your solution would require additional code, whereas in the code i provided that would be just another print statememt or smth quick. Anyway, thanks! – vlad-ardelean Jan 19 '15 at 14:26
  • 1
    True, though that's basically because this solution is less verbose to begin with. A simple `[name for name in dict1.keys() if dict1[name] != dict2[name]]` would give you all the keys that are different, given that `dict1.keys() == dict2.keys()` because they are the field names. – knbk Jan 19 '15 at 15:02