Skip to content

Fix 29291 negated q when expression #19712

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Jkhall81
Copy link
Contributor

@Jkhall81 Jkhall81 commented Aug 7, 2025

Trac ticket number

ticket-29291

Branch description

This PR fixes a long-standing issue where using a negated Q() object inside a When() expression would result in incorrect SQL due to improper join handling across nullable relationships.

Previously, annotations like:

annotate(
    flag=Case(
        When(~Q(related_model__field=True), then=Value(True)),
        default=Value(False),
    )
)

would generate broken or incomplete SQL when traversing nullable FKs. This patch updates When.as_sql() to delegate condition compilation to the query's internal _add_q() logic using query.build_filter(...), ensuring consistent handling of negation, joins, and subquery pushdowns -- just like .filter().

This patch includes:

  • A new test class documenting expected behavior and edge cases
  • Full test coverage comparing annotated vs filtered queries.
  • No changes to behavior for non-Q conditions

Checklist

  • This PR targets the main branch.
  • The commit message is written in past tense, mentions the ticket number, and ends with a period.
  • I have checked the "Has patch" ticket flag in the Trac system.
  • I have added or updated relevant tests.
  • I have added or updated relevant docs, including release notes if applicable.
  • I have attached screenshots in both light and dark modes for any UI changes.

@github-actions github-actions bot added the no ticket Based on PR title, no linked Trac ticket label Aug 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no ticket Based on PR title, no linked Trac ticket
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant