Django comparing model instances for equality

后端 未结 8 1773
夕颜
夕颜 2020-12-01 11:53

I understand that, with a singleton situation, you can perform such an operation as:

spam == eggs

and if spam and eggs

8条回答
  •  再見小時候
    2020-12-01 12:17

    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 ?

提交回复
热议问题