1

i have a table which i would like to group by integer range (ages). table for example:

Name   Age
John   21
Steve  24
Dan    29 
Mike   31 

my expected result is to group the name by age ranges for example [21-28] [29-33] so what i'll get is the following result:

[21-28] [29-33]
  John    Dan
  Steve   Mike

i was playing around with the annotate function of Django but couldn't figure it out so far.

any suggestions?

gil
  • 2,388
  • 1
  • 21
  • 29

2 Answers2

4

If you want to annotate which age group it belongs to use conditional annotation(Case) like this:

from django.db.models import Case, CharField, Value, When

Person.objects.annotate(
     age_group = Case(
          When(age__range=[21, 27], value=Value('21-27')),
          When(age__range=[29, 33], value=Value('29-33')),
          default=Value('No group'),
          output_field=CharField(),
     )
).values('age', 'age_group')
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • in django 2.2 it's When(age__range=[21, 27], then=Value('21-27')), instead of When(age__range=[21, 27], value=Value('21-27')), – gil Mar 09 '20 at 11:57
0

Looks like you have a finite number of groups, why not do a query for each and every one?

21_28_group = Person.objects.filter(age__gte=21).filter(age__lte=28)
29_33_group = Person.objects.filter(age__gte=29).filter(age__lte=33)
Horatiu Jeflea
  • 7,256
  • 6
  • 38
  • 67
  • that's what i used so far but the performance wasn't good enough. went for annotate since i thought it could be achieved in 1 query to db – gil Mar 05 '20 at 08:11