From baa960209f4f946d333987fbabcf13d26abfeb89 Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Sun, 28 Sep 2008 04:36:10 +0000 Subject: [PATCH] Fixed Queryset.dates() in the presence of extra-select columns. Any extra(select=...) columns can be ignored in the SQL for dates, since we are only interested in extracting distinct date values. We were previously including them by accident and it was generating incorrect SQL. git-svn-id: http://code.djangoproject.com/svn/django/trunk@9091 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/sql/subqueries.py | 1 + tests/regressiontests/extra_regress/models.py | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py index 77b5d6cf37..8a2493e80f 100644 --- a/django/db/models/sql/subqueries.py +++ b/django/db/models/sql/subqueries.py @@ -394,6 +394,7 @@ class DateQuery(Query): self.select = [select] self.select_fields = [None] self.select_related = False # See #7097. + self.extra_select = {} self.distinct = True self.order_by = order == 'ASC' and [1] or [-1] diff --git a/tests/regressiontests/extra_regress/models.py b/tests/regressiontests/extra_regress/models.py index 5a98a5dac4..680917b8ae 100644 --- a/tests/regressiontests/extra_regress/models.py +++ b/tests/regressiontests/extra_regress/models.py @@ -1,4 +1,5 @@ import copy +import datetime from django.contrib.auth.models import User from django.db import models @@ -9,6 +10,7 @@ from django.utils.datastructures import SortedDict class RevisionableModel(models.Model): base = models.ForeignKey('self', null=True) title = models.CharField(blank=True, max_length=255) + when = models.DateTimeField(default=datetime.datetime.now) def __unicode__(self): return u"%s (%s, %s)" % (self.title, self.id, self.base.id) @@ -31,12 +33,13 @@ class Order(models.Model): __test__ = {"API_TESTS": """ # Regression tests for #7314 and #7372 ->>> rm = RevisionableModel.objects.create(title='First Revision') +>>> rm = RevisionableModel.objects.create(title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0)) >>> rm.pk, rm.base.pk (1, 1) >>> rm2 = rm.new_revision() >>> rm2.title = "Second Revision" +>>> rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0) >>> rm2.save() >>> print u"%s of %s" % (rm2.title, rm2.base.title) Second Revision of First Revision @@ -107,4 +110,9 @@ True >>> User.objects.filter(pk=u.id).extra(select={'extra_field': 1}, order_by=['extra_field']).distinct() [] +# When calling the dates() method on a queryset with extra selection columns, +# we can (and should) ignore those columns. They don't change the result and +# cause incorrect SQL to be produced otherwise. +>>> RevisionableModel.objects.extra(select={"the_answer": 'id'}).dates('when', 'month') +[datetime.datetime(2008, 9, 1, 0, 0)] """}