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

refactor: add __eq__ on Table #1098

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions piccolo/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,11 @@ def __repr__(self) -> str:
)
return f"<{self.__class__.__name__}: {pk}>"

def __eq__(self, other) -> bool:
return isinstance(other, self.__class__) and getattr(
self, self._meta.primary_key._meta.name, None
) == getattr(other, other._meta.primary_key._meta.name, None)

###########################################################################
# Classmethods

Expand Down
31 changes: 31 additions & 0 deletions tests/table/instance/test_instance_equality.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from piccolo.testing.test_case import AsyncTableTest
from tests.example_apps.music.tables import Band, Manager


class TestInstanceEquality(AsyncTableTest):
tables = [Manager, Band]

async def asyncSetUp(self):
await super().asyncSetUp()

self.manager = Manager(name="Guido")
await self.manager.save()

self.band = Band(
name="Pythonistas", manager=self.manager.id, popularity=100
)
await self.band.save()

async def test_instance_equality(self) -> None:
"""
Make sure for instance equailty.
"""
band_pk = await self.band.objects().first()
band = await self.band.objects(Band.manager).get(
(Band._meta.primary_key == band_pk.id)
)
manager_pk = await self.manager.objects().first()
manager = await self.manager.objects().get(
Manager._meta.primary_key == manager_pk.id
)
self.assertTrue(band.manager == manager)
Loading