Django comparing model instances for equality

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.


The source code for model instance equality is this (from Django 4.0.5):

def __eq__(self, other):
    if not isinstance(other, Model):
        return NotImplemented
    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.)


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 ?