6

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?

Amir
  • 717
  • 2
  • 9
  • 21

1 Answers1

11

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.

knbk
  • 52,111
  • 9
  • 124
  • 122