diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 82d22d6e2..d58bf8594 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -26,6 +26,7 @@ Added - Add binary compression support for `UUIDField` in `MySQL`. (#1458) - Only `Model`, `Tortoise`, `BaseDBAsyncClient`, `__version__`, and `connections` are now exported from `tortoise` - Add parameter `validators` to `pydantic_model_creator`. (#1471) +- Add __eq__ method to Q to more easily test dynamically-built queries (#1506) Fixed ^^^^^ diff --git a/tests/test_q.py b/tests/test_q.py index 82e78f759..61a58c942 100644 --- a/tests/test_q.py +++ b/tests/test_q.py @@ -92,6 +92,27 @@ def test_q_partial_or(self): self.assertEqual(q.filters, {"moo": "cow"}) self.assertEqual(q.join_type, "OR") + def test_q_equality(self): + # basic query + basic_q1 = Q(moo="cow") + basic_q2 = Q(moo="cow") + self.assertEqual(basic_q1, basic_q2) + + # and query + and_q1 = Q(firstname="John") & Q(lastname="Doe") + and_q2 = Q(firstname="John") & Q(lastname="Doe") + self.assertEqual(and_q1, and_q2) + + # or query + or_q1 = Q(firstname="John") | Q(lastname="Doe") + or_q2 = Q(firstname="John") | Q(lastname="Doe") + self.assertEqual(or_q1, or_q2) + + # complex query + complex_q1 = (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane") + complex_q2 = (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane") + self.assertEqual(complex_q1, complex_q2) + class TestQCall(TestCase): def test_q_basic(self): diff --git a/tortoise/expressions.py b/tortoise/expressions.py index a3a3df093..55a9c58e2 100644 --- a/tortoise/expressions.py +++ b/tortoise/expressions.py @@ -191,6 +191,13 @@ def __invert__(self) -> "Q": q.negate() return q + def __eq__(self, other: "Q") -> bool: + return ( + self.children == other.children + and self.join_type == other.join_type + and self.filters == other.filters + ) + def negate(self) -> None: """ Negates the current Q object. (mutation)