Ticket #4157: 5079-better_patch_for_is_equal_check_2.diff

File 5079-better_patch_for_is_equal_check_2.diff, 1.9 KB (added by Michael Axiak <axiak@…>, 8 years ago)

This works a little better.

  • 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        if excludes is not None:
     104            field_excludes = excludes
     105        elif self._meta.equality_exclude is not None:
     106            field_excludes = self._meta.equality_exclude
     107        else:
     108            field_excludes = [self._meta.pk.attname]       
     109
     110        field_names = [field.attname for field in self._meta.fields
     111                       if field.attname not in field_excludes           ]
     112
     113        for field_name in field_names:
     114            if getattr(self, field_name) != getattr(other, field_name):
     115                return False
     116        return True   
     117
    91118    def __eq__(self, other):
    92119        return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
    93120
  • 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