Skip to content
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

Refs #34007 -- Added Q.referenced_based_fields property #18093

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions django/db/models/query_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,19 @@ def __eq__(self, other):
def __hash__(self):
return hash(self.identity)

@cached_property
def referenced_base_fields(self):
"""
Retrieve all base fields referenced directly or through F expressions
excluding any fields referenced through joins.
"""
# Avoid circular imports.
from django.db.models.sql import query

return {
child.split(LOOKUP_SEP, 1)[0] for child in query.get_children_from_q(self)
}


class DeferredAttribute:
"""
Expand Down
28 changes: 28 additions & 0 deletions tests/queries/test_q.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
)
from django.db.models.expressions import NegatedExpression, RawSQL
from django.db.models.functions import Lower
from django.db.models.lookups import Exact, IsNull
from django.db.models.sql.where import NothingNode
from django.test import SimpleTestCase, TestCase

Expand Down Expand Up @@ -263,6 +264,33 @@ def test_create_helper(self):
Q(*items, _connector=connector),
)

def test_referenced_base_fields(self):
# Make sure Q.referenced_base_fields retrieves all base fields from
# both filters and F expressions.
tests = [
(Q(field_1=1) & Q(field_2=1), {"field_1", "field_2"}),
(
Q(Exact(F("field_3"), IsNull(F("field_4"), True))),
{"field_3", "field_4"},
),
(Q(Exact(Q(field_5=F("field_6")), True)), {"field_5", "field_6"}),
(Q(field_2=1), {"field_2"}),
(Q(field_7__lookup=True), {"field_7"}),
(Q(field_7__joined_field__lookup=True), {"field_7"}),
]
combined_q = Q(1)
combined_q_base_fields = set()
for q, expected_base_fields in tests:
combined_q &= q
combined_q_base_fields |= expected_base_fields
tests.append((combined_q, combined_q_base_fields))
for q, expected_base_fields in tests:
with self.subTest(q=q):
self.assertEqual(
q.referenced_base_fields,
expected_base_fields,
)


class QCheckTests(TestCase):
def test_basic(self):
Expand Down