diff --git a/sqlmodel/main.py b/sqlmodel/main.py index 9e8330d69d..2b13f8e0fb 100644 --- a/sqlmodel/main.py +++ b/sqlmodel/main.py @@ -735,6 +735,21 @@ def __repr_args__(self) -> Sequence[Tuple[Optional[str], Any]]: if not (isinstance(k, str) and k.startswith("_sa_")) ] + def __hash__(self) -> int: + # If there's a primary key, use that to hash the object + to_hash = "" + + for field in self.__fields__: + is_primary_key = getattr( + self.__fields__[field].field_info, "primary_key", False + ) + if is_primary_key: + to_hash += str(getattr(self, field)) + if not to_hash: + # Can't call super().__hash__ because BaseModel.__hash__ is a NoneType + raise TypeError(f"unhashable type: '{self.__class__.__name__}'") + return hash(to_hash) + @declared_attr # type: ignore def __tablename__(cls) -> str: return cls.__name__.lower()