views:

1911

answers:

3

How can i create simple group by query in trunk version of django?

I need something like

SELECT name
FROM mytable
GROUP BY name

actually what i want to do is simply get all entries with distinct names.

+2  A: 

Add .distinct to your queryset:

Entries.objects.filter(something='xxx').distinct()
Parand
+2  A: 

this will not work because every row have unique id. So every record is distinct..

To solve my problem i used

foo = Foo.objects.all()
foo.query.group_by = ['name']

but this is not official API.

Unfortunately this doesn't work in django 1.2 alpha
t0ster
+7  A: 

If you need all the distinct names, just do this:

Foo.objects.values('name').distinct()

And you'll get a list of dictionaries, each one with a name key. If you need other data, just add more attribute names as parameters to the .values() call. Of course, if you add in attributes that may vary between rows with the same name, you'll break the .distinct().

This won't help if you want to get complete model objects back. But getting distinct names and getting full data are inherently incompatible goals anyway; how do you know which row with a given name you want returned in its entirety? If you want to calculate some sort of aggregate data for all the rows with a given name, aggregation support was recently added to Django trunk and can take care of that for you.

Carl Meyer