Django comparing model instances for equality
I understand that, with a singleton situation, you can perform such an operation as:
spam == eggs
and if spam
and eggs
are instances of the same class with all the same attribute values, it will return True
. In a Django model, this is natural because two separate instances of a model won't ever be the same unless they have the same .pk
value.
The problem with this is that if a reference to an instance has attributes that have been updated by middleware somewhere along the way and it hasn't been saved, and you're trying to it to another variable holding a reference to an instance of the same model, it will return False
of course because they have different values for some of the attributes. Obviously, I don't need something like a singleton, but I'm wondering if there some official Djangonic (ha, a new word) method for checking this, or if I should simply check that the .pk
value is the same, by running:
spam.pk == eggs.pk
I'm sorry if this was a huge waste of time, but it just seems like there might be a method for doing this and something I'm missing that I'll regret down the road if I don't find it.
UPDATE (02-27-2015)
You should disregard the first part of this question since you shouldn't compare singletons with ==
, but rather with is
. Singletons really have nothing to do with this question.
Solution 1:
From Django documentation:
To compare two model instances, just use the standard Python comparison operator, the double equals sign: ==
. Behind the scenes, that compares the primary key values of two models.
Solution 2:
spam.pk == eggs.pk
is a good way to do that.
You may add __eq__
to your model but I will avoid that, because it is confusing as ==
can mean different things in different contexts, e.g. I may want ==
to mean content is same, id may differ, so again best way is
spam.pk == eggs.pk
Edit:
btw in django 1.0.2 Model class has defined __eq__
as
def __eq__(self, other):
return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
which seems to be same as spam.pk == eggs.pk as pk
is property which uses _get_pk_val
so I don't see why spam == eggs
is not working ?
Solution 3:
As of Django 3.0.2, the source code for model instance equality is this:
def __eq__(self, other):
if not isinstance(other, Model):
return False
if self._meta.concrete_model != other._meta.concrete_model:
return False
my_pk = self.pk
if my_pk is None:
return self is other
return my_pk == other.pk
That is, two model instances are equal if they come from the same database table and have the same primary key. If either primary key is None
they're only equal if they're the same object.
(So getting back to the OP's question, simply comparing the instances would be fine.)
Solution 4:
You can define the Class' __eq__
method to chage that behaviour:
http://docs.python.org/reference/datamodel.html