Django comparing model instances for equality

后端 未结 8 1650
夕颜
夕颜 2020-12-01 11:53

I understand that, with a singleton situation, you can perform such an operation as:

spam == eggs

and if spam and eggs

相关标签:
8条回答
  • 2020-12-01 12:28

    You can define the Class' __eq__ method to chage that behaviour:

    http://docs.python.org/reference/datamodel.html

    0 讨论(0)
  • 2020-12-01 12:34

    from https://djangosnippets.org/snippets/2281/

    i changed to compare two instance and return Boolean value

    def is_same(self, obj):
        excluded_keys = 'timestamp', 'creator_id' # creater_id is one foreign key ins table
        return _is_same(self, obj, excluded_keys)
    
    
    def _is_same(obj1, obj2, excluded_keys):
        d1, d2 = obj1.__dict__, obj2.__dict__
        for k, v in d1.items():
             # print('check key: ' + k)
            if k in excluded_keys or k in ['_state', '_django_cleanup_original_cache']: # _state make difference so automatically exclude it
                # print(k + ' is in excluded keys')
                continue
    
            if v != d2[k]:
                # print('value in not equal in second object')
                return False
            else:
                # print('it is same')
                continue
    
        # print('all keys checked, so both object is same')
        return True
    
    0 讨论(0)
提交回复
热议问题