Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query model - GROUP BY, MIN, MAX

I'm having trouble transferring my query to django. In sqlite3 it looked like this:

SELECT A, MIN(B), MAX(B) from table GROUP BY A

This would output unique values from A with a range of values from B Any hints on how to approach this? Is it even possible in django?

like image 262
Amir Avatar asked Sep 14 '15 09:09

Amir


1 Answers

You can use values() for the GROUP BY, and annotate() for the MIN and MAX:

from django.db.models import Min, Max

MyModel.objects.values('A').annotate(min_b=Min('B'), max_b=Max('B'))

You'll get a list of dictionaries, containing the keys A, min_b and max_b.

like image 125
knbk Avatar answered Oct 22 '22 02:10

knbk