Search code examples
pythondjangopython-itertools

Grouping Django Model Instances


I've looked around and can't find anything exactly like this, so I'm asking...

I have a database with all 50 US States and their populations are stored in an integer field. None of the populations are the same.

I would like to create 10 groups of 5 states ordered by population size, so the five most populous states are in Group One, five next most populous in Group Two, and so on.

I'm creating a data migration to form these groups and save the groupings and I'm not sure how to iterate over the instances.


Solution

  • size_of_group = 5
    all_states = State.objects.order_by('-population')
    grouped_states = [all_states[i:i + size_of_group] for i in xrange(0, len(all_states), size_of_group)]
    

    It will give You a list of sublists. Each sublist contains size_of_group states. grouped_states[0] have 5 with biggest populations. '-population' says that the order is descending.

    Assuming Your model looks like:

    class State(models.Model)
      population = models.IntegerField()