Skip to content

Commit

Permalink
Fixed #14700 -- ensure that a raw query is only executed once per ite…
Browse files Browse the repository at this point in the history
…ration.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14785 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
alex committed Dec 3, 2010
1 parent 5475da1 commit d68598e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 6 additions & 2 deletions django/db/models/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -1310,9 +1310,13 @@ def __iter__(self):

# Cache some things for performance reasons outside the loop.
db = self.db
compiler = connections[db].ops.compiler('SQLCompiler')(self.query, connections[db], db)
compiler = connections[db].ops.compiler('SQLCompiler')(
self.query, connections[db], db
)
need_resolv_columns = hasattr(compiler, 'resolve_columns')

query = iter(self.query)

# Find out which columns are model's fields, and which ones should be
# annotated to the model.
for pos, column in enumerate(self.columns):
Expand Down Expand Up @@ -1341,7 +1345,7 @@ def __iter__(self):
if need_resolv_columns:
fields = [self.model_fields.get(c, None) for c in self.columns]
# Begin looping through the query values.
for values in self.query:
for values in query:
if need_resolv_columns:
values = compiler.resolve_columns(values, fields)
# Associate fields to values
Expand Down
5 changes: 5 additions & 0 deletions tests/modeltests/raw_query/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,8 @@ def test_inheritance(self):
self.assertEqual(
[o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk]
)

def test_query_count(self):
self.assertNumQueries(1,
list, Author.objects.raw("SELECT * FROM raw_query_author")
)

0 comments on commit d68598e

Please sign in to comment.