feat: q to bool#2227
Open
VladislavYar wants to merge 1 commit into
Open
Conversation
waketzheng
reviewed
Jun 24, 2026
| assert bool(q_empty) is False | ||
| assert bool(q_children) is True | ||
| assert bool(q_children_empty) is False | ||
|
|
Contributor
There was a problem hiding this comment.
Please add more test cases, such as:
q = ~q
q = Q(Q(), Q(), join_type='OR')
...
waketzheng
reviewed
Jun 24, 2026
| ) | ||
|
|
||
| def __bool__(self) -> bool: | ||
| return any((self.filters, *(children for children in self.children))) |
Contributor
There was a problem hiding this comment.
How about using the following code?
if self.filters:
return True
return any(self.children)
waketzheng
reviewed
Jun 24, 2026
waketzheng
left a comment
Contributor
There was a problem hiding this comment.
It would be better to also update the changelog.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Added
__bool__support to theQclass, allowingQobjects to be evaluated in a boolean context.A
Qobject is considered truthy if it contains any filters or any non-empty children. An emptyQ()with no filters and no children evaluates toFalse.Motivation and Context
Previously, all
Qinstances were truthy by default (standard Python object behavior), making it impossible to distinguish between an emptyQ()and a meaningful one. This change enables natural boolean checks likeif q:to guard against applying empty query conditions.How Has This Been Tested?
Added
test_q_to_boolcovering four cases:Q(row="data")- truthy (has filters)Q()- falsy (no filters, no children)Q(Q(row="data"), Q(row="data"))- truthy (has non-empty children)Q(Q(), Q())- falsy (all children are empty)Checklist: