Skip to content

Commit 42dc3b9

Browse files
committed
queryset-refactor: Fixed the interaction between extra(select=...) and
valuelist(). Fixed django#7053. git-svn-id: http://code.djangoproject.com/svn/django/branches/queryset-refactor@7446 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 42260ef commit 42dc3b9

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

django/db/models/query.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -557,13 +557,21 @@ def _merge_sanity_check(self, other):
557557

558558
class ValuesListQuerySet(ValuesQuerySet):
559559
def iterator(self):
560-
self.field_names.extend([f for f in self.query.extra_select.keys()])
560+
self.query.trim_extra_select(self.extra_names)
561561
if self.flat and len(self._fields) == 1:
562562
for row in self.query.results_iter():
563563
yield row[0]
564-
else:
564+
elif not self.query.extra_select:
565565
for row in self.query.results_iter():
566566
yield row
567+
else:
568+
# When extra(select=...) is involved, the extra cols come are
569+
# always at the start of the row, so we need to reorder the fields
570+
# to match the order in self._fields.
571+
names = self.query.extra_select.keys() + self.field_names
572+
for row in self.query.results_iter():
573+
data = dict(zip(names, row))
574+
yield tuple([data[f] for f in self._fields])
567575

568576
def _clone(self, *args, **kwargs):
569577
clone = super(ValuesListQuerySet, self)._clone(*args, **kwargs)

tests/modeltests/lookup/models.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,13 @@ def __unicode__(self):
180180
>>> Article.objects.valueslist('id', flat=True).order_by('id')
181181
[1, 2, 3, 4, 5, 6, 7]
182182
183+
>>> Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').valueslist('id')
184+
[(1,), (2,), (3,), (4,), (5,), (6,), (7,)]
185+
>>> Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').valueslist('id_plus_one', 'id')
186+
[(2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6), (8, 7)]
187+
>>> Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').valueslist('id', 'id_plus_one')
188+
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]
189+
183190
>>> Article.objects.valueslist('id', 'headline', flat=True)
184191
Traceback (most recent call last):
185192
...

0 commit comments

Comments
 (0)