Skip to content

Commit 7659e33

Browse files
committed
feat: q to bool (add edge case tests, update changelog)
1 parent 67f957a commit 7659e33

3 files changed

Lines changed: 9 additions & 1 deletion

File tree

CHANGELOG.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Added
1717
- ``QuerySet.contains()`` method to check if an object exists in a queryset.
1818
- Added comprehensive EXPLAIN support for MySQL and PostgreSQL.
1919
- Built-in ``DomainNameValidator``, ``URLValidator``, and ``EmailValidator`` classes for common validation patterns. (#2162)
20+
- ``Q.__bool__()`` so ``Q`` objects with no filters/children (including nested empty ``Q`` children) are falsy.
2021

2122
Fixed
2223
^^^^^

tests/test_q.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,18 @@ def test_q_basic():
2121

2222
def test_q_to_bool():
2323
q = Q(row="data")
24+
q_negative = ~q
2425
q_empty = Q()
2526
q_children = Q(Q(row="data"), Q(row="data"))
2627
q_children_empty = Q(Q(), Q())
28+
q_children_empty_join_type_or = Q(Q(), Q(), join_type="OR")
2729
assert bool(q) is True
30+
assert bool(q_negative) is True
31+
assert bool(q_negative) is True
2832
assert bool(q_empty) is False
2933
assert bool(q_children) is True
3034
assert bool(q_children_empty) is False
35+
assert bool(q_children_empty_join_type_or) is False
3136

3237

3338
def test_q_compound():

tortoise/expressions.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,9 @@ def __eq__(self, other: object) -> bool:
327327
)
328328

329329
def __bool__(self) -> bool:
330-
return any((self.filters, *(children for children in self.children)))
330+
if self.filters:
331+
return True
332+
return any(self.children)
331333

332334
def negate(self) -> None:
333335
"""

0 commit comments

Comments
 (0)