Observed on rev 183
Given a couple of models like the following
class Person(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50)
class PersonShoes(models.Model): id = models.AutoField(primary_key=True) person = models.ForeignKey(Person, related_name='shoes') brand = models.CharField(max_length=50)
If you wanted to query a list of people ordered by the number of shoes they own the django methodology for this would be:
peopleByShoeCount = Person.objects.annotate(num_shoes=Count('shoes')).order_by('num_shoes')
But when attempting this query with a django-pyodbc backend the following error is given:
[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'num_shoes'.
Comment #1
Posted on Dec 14, 2010 by Happy KangarooQuick correction. The error seems to only occur when attempting to slice the result set, like when attempting to get the top 10 results.
Person.objects.annotate(num_shoes=Count('shoes')).order_by('num_shoes')[:10]
Comment #2
Posted on Jan 8, 2011 by Helpful HorseTojiro,
The problem is due to the fact that MS SQL doesn't allow you to use column aliases in the ORDER BY clause which is needed when you want to take a slice. Apply the attached patch to sql_server/pyodbc/query.py
This is an ugly patch but it works.
- aggregate_patch.diff 1.16KB
Comment #3
Posted on Mar 24, 2011 by Swift Panda(No comment was entered for this change.)
Status: Accepted
Labels:
Type-Defect
Priority-Medium