Django Group

How to create a simple group on demand in the trunk django version?

I need something like

SELECT name
FROM mytable
GROUP BY name

in fact, what I want to do is just get all the records with different names.

+3
source share
3 answers

If you need all the different names, just do the following:

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

And you will get a list of dictionaries, each of which has a name . If you need other data, just add more attribute names as parameters to call .values ​​(). Of course, if you add attributes that can change between lines with the same name, you break .distinct ().

, . ; , ? - , ​​ Django .

+12

.distinct :

Entries.objects.filter(something='xxx').distinct()
+3

this will not work because each row has a unique identifier. Therefore, each entry is different.

To solve my problem, I used

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

but this is not an official API.

+2
source

Source: https://habr.com/ru/post/1702172/


All Articles