Skip to content

Commit

Permalink
Fixed #28289 -- Fixed raw sql annotations with QuerySet methods on in…
Browse files Browse the repository at this point in the history
…herited model fields.
  • Loading branch information
can committed May 20, 2019
1 parent 7c3732a commit 96ec27f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions django/db/models/expressions.py
Expand Up @@ -689,6 +689,17 @@ def as_sql(self, compiler, connection):
def get_group_by_cols(self, alias=None):
return [self]

def resolve_expression(self, query=None, allow_joins=True, reuse=None,
summarize=False, for_save=False, simple_col=False):
other_fields = (set(query.model._meta.get_fields()) -
set(query.model._meta.get_fields(include_parents=False)))
for field in other_fields:
if field.name in self.sql:
query.resolve_ref(field.name, allow_joins, reuse, summarize, simple_col)
break

return super().resolve_expression(query, allow_joins, reuse, summarize, for_save)


class Star(Expression):
def __repr__(self):
Expand Down
20 changes: 20 additions & 0 deletions tests/annotations/tests.py
Expand Up @@ -405,6 +405,26 @@ def test_order_by_aggregate(self):
lambda a: (a['age'], a['age_count'])
)

def test_child_with_raw_sql_annotation_on_parent(self):
DepartmentStore.objects.create(
name='Angus & Robinson',
original_opening=datetime.date(2014, 3, 8),
friday_night_closing=datetime.time(21, 00, 00),
chain='Westfield',
)
tests = (
('name', ()),
('case when name="foo" then "oof" else name end', ())
)
from django.db.models.expressions import RawSQL
for sql, params in tests:
with self.subTest(sql=sql):
self.assertSequenceEqual(
DepartmentStore.objects.annotate(
title=RawSQL(sql, params)).values_list('title', flat=True),
['Angus & Robinson']
)

def test_annotate_exists(self):
authors = Author.objects.annotate(c=Count('id')).filter(c__gt=1)
self.assertFalse(authors.exists())
Expand Down

0 comments on commit 96ec27f

Please sign in to comment.