diff --git a/django/db/models/query.py b/django/db/models/query.py
index d448dec..d0803c4 100644
a
|
b
|
class QuerySet(object):
|
267 | 267 | model_cls = deferred_class_factory(self.model, skip) |
268 | 268 | |
269 | 269 | compiler = self.query.get_compiler(using=self.db) |
| 270 | db = self.db |
270 | 271 | for row in compiler.results_iter(): |
271 | 272 | if fill_cache: |
272 | 273 | obj, _ = get_cached_row(self.model, row, |
… |
… |
class QuerySet(object):
|
283 | 284 | obj = self.model(*row[index_start:aggregate_start]) |
284 | 285 | |
285 | 286 | # Store the source database of the object |
286 | | obj._state.db = self.db |
| 287 | obj._state.db = db |
287 | 288 | |
288 | | for i, k in enumerate(extra_select): |
289 | | setattr(obj, k, row[i]) |
| 289 | if extra_select: |
| 290 | for i, k in enumerate(extra_select): |
| 291 | setattr(obj, k, row[i]) |
290 | 292 | |
291 | 293 | # Add the aggregates to the model |
292 | | for i, aggregate in enumerate(aggregate_select): |
293 | | setattr(obj, aggregate, row[i+aggregate_start]) |
| 294 | if aggregate_select: |
| 295 | for i, aggregate in enumerate(aggregate_select): |
| 296 | setattr(obj, aggregate, row[i+aggregate_start]) |
294 | 297 | |
295 | 298 | yield obj |
296 | 299 | |
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index a11d556..b2249dc 100644
a
|
b
|
class SQLCompiler(object):
|
672 | 672 | """ |
673 | 673 | resolve_columns = hasattr(self, 'resolve_columns') |
674 | 674 | fields = None |
| 675 | has_aggregate_select = bool(self.query.aggregate_select) |
675 | 676 | for rows in self.execute_sql(MULTI): |
676 | 677 | for row in rows: |
677 | 678 | if resolve_columns: |
… |
… |
class SQLCompiler(object):
|
692 | 693 | f.column in only_load[db_table]] |
693 | 694 | row = self.resolve_columns(row, fields) |
694 | 695 | |
695 | | if self.query.aggregate_select: |
| 696 | if has_aggregate_select: |
696 | 697 | aggregate_start = len(self.query.extra_select.keys()) + len(self.query.select) |
697 | 698 | aggregate_end = aggregate_start + len(self.query.aggregate_select) |
698 | 699 | row = tuple(row[:aggregate_start]) + tuple([ |