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@…>, 18 years ago)

Cleaner Patch, now uses new Meta equality_exclude parameter

  • db/models/base.py

     
    8888    def __str__(self):
    8989        return '%s object' % self.__class__.__name__
    9090
     91    def is_equal(self, other, excludes = None):
     92        """
     93        Returns a boolean if the two instances of a model are equal.
     94        If ``excludes`` is specified, all fields with the names given in
     95        ``excludes`` will not be considered in the comparison.
     96        If ``excludes`` is not specified, it will default to be the
     97        primary key.
     98        """
     99        if self is other: return True
     100        if type(self) != type(other): return False
     101
     102        # TODO: Handle for multiple pk fields if that ever happens
     103        field_excludes = []
     104        if excludes is not None:
     105            field_excludes += excludes
     106        if self._meta.equality_exclude is not None:
     107            field_excludes += self._meta.equality_exclude
     108        if excludes is None and self._meta.equality_exclude is None:
     109            field_excludes = [self._meta.pk.attname]       
     110
     111        field_names = [field.attname for field in self._meta.fields
     112                       if field.attname not in field_excludes           ]
     113
     114        for field_name in field_names:
     115            if getattr(self, field_name) != getattr(other, field_name):
     116                return False
     117        return True
     118       
     119
    91120    def __eq__(self, other):
    92121        return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
    93122
  • db/models/options.py

     
    3333        self.has_auto_field = False
    3434        self.one_to_one_field = None
    3535        self.parents = []
     36        self.equality_exclude = None
    3637
    3738    def contribute_to_class(self, cls, name):
    3839        cls._meta = self
Back to Top