[Django]-Group by in django

12👍

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.

3👍

Add .distinct to your queryset:

Entries.objects.filter(something='xxx').distinct()
👤Parand

2👍

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.

Leave a comment