On 11/10/07, Steve Freitas <[EMAIL PROTECTED]> wrote: > > Hi all, > > I'm looking to get the sum of a column. I've seen plenty of examples > which illustrate using a QuerySet's extra(select={'foo': 'sum(bar)'}) > method, but my Postgres pukes on that: > > ERROR: column "app_model.id" must appear in the GROUP BY clause or be > used in an aggregate function > > After messing about I figured out that's because Django is asking for > every field in the table. If it would only ask for sum(bar), it'd work > great. So I need to override the QuerySet's SELECT statement... So, > write a custom Manager! Except that when I'm ready to ask for the sum, > I've spent a bunch of time filter()ing a QuerySet. And I'd like to use > all the QuerySet's built-in intelligence about the WHERE clause, the > table, etc., and I haven't seen how to make a Manager that modifies the > SELECT statement, but leaves the rest of the functionality there. > > Any help would be much appreciated.
You have at least 3 options: 1) Get hold of a cursor and write the full SQL query you want yourself. It sounds like all you want is SELECT SUM(bar) FROM MYTABLE, so this may be the easiest and most stable solution. 2) Use the extra clause to fake the WHERE clause. You'll need to experiment a bit, but as I recall, you can put a WHERE statement that lists the fields into one of the arguments, and as a result of the way Django forms it's queries, the WHERE clause will end up in the right place. This is particularly hacky, and certainly won't be guaranteed to work once the queryset refactor lands. 3) Specifying q.values('foo').extra(select={'foo': 'sum(bar)'}) - i.e., specifically request _no_ column values, other than the extra column. > ...sure is ugly. I know there's been work on getting aggregation going > since early last year, but isn't there a place for a simple function > (that won't take years to get into trunk) like, say, distinct('field')? There might be. However, we're not going to add a method to the API before we've had the full discussion on what the final form of aggregation will look like. The one thing we don't want to do is add a function, then take it away (or change it in some backwards incompatible way) at some later date once we've had the design discussion. Yours, Russ Magee %-) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---