Skip to content

Commit dcda944

Browse files
Added hash function to models with primary keys
1 parent c75743d commit dcda944

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

sqlmodel/main.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,21 @@ def __repr_args__(self) -> Sequence[Tuple[Optional[str], Any]]:
735735
if not (isinstance(k, str) and k.startswith("_sa_"))
736736
]
737737

738+
def __hash__(self) -> int:
739+
# If there's a primary key, use that to hash the object
740+
to_hash = ""
741+
742+
for field in self.__fields__:
743+
is_primary_key = getattr(
744+
self.__fields__[field].field_info, "primary_key", False
745+
)
746+
if is_primary_key:
747+
to_hash += str(getattr(self, field))
748+
if not to_hash:
749+
# Can't call super().__hash__ because BaseModel.__hash__ is a NoneType
750+
raise TypeError(f"unhashable type: '{self.__class__.__name__}'")
751+
return hash(to_hash)
752+
738753
@declared_attr # type: ignore
739754
def __tablename__(cls) -> str:
740755
return cls.__name__.lower()

0 commit comments

Comments
 (0)