Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add hash to model with primary key #877

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading