Code

Ticket #4157: 5079-better_patch_for_is_equal_check.diff

File 5079-better_patch_for_is_equal_check.diff, 2.0 KB (added by Michael Axiak <axiak@…>, 7 years ago)

Cleaner Patch, now uses new Meta equality_exclude parameter

Line 
1Index: db/models/base.py
2===================================================================
3--- db/models/base.py   (revision 5079)
4+++ db/models/base.py   (working copy)
5@@ -88,6 +88,35 @@
6     def __str__(self):
7         return '%s object' % self.__class__.__name__
8 
9+    def is_equal(self, other, excludes = None):
10+        """
11+        Returns a boolean if the two instances of a model are equal.
12+        If ``excludes`` is specified, all fields with the names given in
13+        ``excludes`` will not be considered in the comparison.
14+        If ``excludes`` is not specified, it will default to be the
15+        primary key.
16+        """
17+        if self is other: return True
18+        if type(self) != type(other): return False
19+
20+        # TODO: Handle for multiple pk fields if that ever happens
21+        field_excludes = []
22+        if excludes is not None:
23+            field_excludes += excludes
24+        if self._meta.equality_exclude is not None:
25+            field_excludes += self._meta.equality_exclude
26+        if excludes is None and self._meta.equality_exclude is None:
27+            field_excludes = [self._meta.pk.attname]       
28+
29+        field_names = [field.attname for field in self._meta.fields
30+                       if field.attname not in field_excludes           ]
31+
32+        for field_name in field_names:
33+            if getattr(self, field_name) != getattr(other, field_name):
34+                return False
35+        return True
36+       
37+
38     def __eq__(self, other):
39         return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
40 
41Index: db/models/options.py
42===================================================================
43--- db/models/options.py        (revision 5079)
44+++ db/models/options.py        (working copy)
45@@ -33,6 +33,7 @@
46         self.has_auto_field = False
47         self.one_to_one_field = None
48         self.parents = []
49+        self.equality_exclude = None
50 
51     def contribute_to_class(self, cls, name):
52         cls._meta = self