Saturday, February 26, 2011

Query Builder forgets annotations


It seems the query builder forgets annotations when dealing with joins:

I have this model with Postgresql, Django 1.3 alpha 1 (SVN rev. 15659):

class Corporation(Model):
uuid = UuidField(primary_key=True)

class Branch(Model):
uuid = UuidField(primary_key=True)
corporation = ForeignKey(Corporation, related_name='branches')

Now I want to retrieve the corporations ordered by the number of their

Which fails with:
FieldError: Cannot resolve keyword 'x' into field. Choices are:
branches, uuid in /django/db/models/sql/ in setup_joins, line 1236

SELECT corporation.uuid, COUNT(branch.uuid) AS x FROM corporation LEFT
OUTER JOIN branch ON (corporation.uuid = branch.corporation_id) GROUP BY
corporation.uuid, corporation.uuid

and executing this query manually, with `ORDER BY x` added, gives me
what I want.

Is this a django bug, or by design?

Now until this is fixed, how can I add this manually to the generated
statement? extra(order_by=['x']) also checks fields. But I don't want to
have to resort to completely raw queries…


Pascal Germroth

You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment