Django comparing model instances for equality

后端 未结 8 1777
夕颜
夕颜 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

    As orokusaki comments, "if neither instance has a primary key, it will return true always". If you want this to work, you could extend your model like so:

    def __eq__(self, other):
        eq = isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
    
        if eq and self._get_pk_val() is None:
            return id(self) == id(other)
        return eq
    

提交回复
热议问题