Ticket #4157: 5079-add_is_equal_to_model.diff

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

The code to make it work.

  • django/db/models/base.py

     
    22import django.db.models.manager
    33from django.core import validators
    44from django.core.exceptions import ObjectDoesNotExist
    5 from django.db.models.fields import AutoField, ImageField, FieldDoesNotExist
     5from django.db.models.fields import Field, AutoField, ImageField, FieldDoesNotExist
    66from django.db.models.fields.related import OneToOneRel, ManyToOneRel
    77from django.db.models.query import delete_objects
    88from django.db.models.options import Options, AdminOptions
     
    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        # if pk happens to be a list of fields,
     103        # we should deal with that
     104        if excludes is None:
     105            if isinstance(type(self)._meta.pk, Field):
     106                excludes = [type(self)._meta.pk.attname]
     107            else:
     108                excludes = [field.attname for field in type(self)._meta.pk]
     109
     110        field_names = [field.attname for field in type(self)._meta.fields
     111                       if field.attname not in excludes                  ]
     112        print field_names
     113        for field_name in field_names:
     114            if getattr(self, field.name) != getattr(other, field.name):
     115                return False
     116        return True
     117       
     118
    91119    def __eq__(self, other):
    92120        return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
    93121
Back to Top