Skip to content

Commit a46bf77

Browse files
committed
Implement equality by ID on VirtualModel
1 parent 954a024 commit a46bf77

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ x.x (Unreleased)
66

77
* Add `get_field` and `get_fields` methods to VirtualModel meta class (smark-1)
88
* Add dedicated `DoesNotExist` and `MultipleObjectsReturned` exceptions on VirtualModel
9+
* Implement equality on VirtualModel based on ID
910
* Make properties `start` and `stop` available in addition to `offset` and `limit`
1011
* Short-circuit queries if running on an empty slice
1112
* Fix: When retrieving by index, use a single-item slice instead of running the full query

queryish/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,3 +306,10 @@ def __str__(self):
306306

307307
def __repr__(self):
308308
return f"<{self.__class__.__name__}: {str(self)}>"
309+
310+
def __eq__(self, other):
311+
if type(self) is not type(other):
312+
return False
313+
if self.pk is None:
314+
return other is self
315+
return self.pk == other.pk

tests/test_rest.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,34 @@ def test_instance_from_detail_lookup(self):
604604
self.assertEqual(result.name, "venusaur")
605605
self.assertEqual(result.id, 3)
606606

607+
@responses.activate
608+
def test_equality(self):
609+
responses.add(
610+
responses.GET, "http://example.com/api/countries/",
611+
match=[matchers.query_param_matcher({"id": 4})],
612+
body="""
613+
[
614+
{
615+
"id": 4,
616+
"name": "Japan",
617+
"continent": "asia"
618+
}
619+
]
620+
"""
621+
)
622+
623+
country = Country.objects.get(id=4)
624+
# match by ID and type
625+
self.assertEqual(country, Country(id=4, name="Japan", continent="asia"))
626+
self.assertEqual(country, Country(id=4, name="Nihon", continent="asia"))
627+
self.assertNotEqual(country, Country(id=5, name="China", continent="asia"))
628+
self.assertNotEqual(country, Pokemon(id=4, name="Charmander"))
629+
630+
def test_equality_on_unsaved_objects(self):
631+
obj1 = Country(name="New Country", continent="oceania")
632+
obj2 = Country(name="New Country", continent="oceania")
633+
self.assertEqual(obj1, obj1)
634+
self.assertNotEqual(obj1, obj2)
607635

608636
@responses.activate
609637
def test_in_bulk(self):

0 commit comments

Comments
 (0)