I have a model class “Place”, which has a field for “state”, and I would like to get a list of querysets grouped by all available distinct states in the DB.
I am currently doing this:
place_list = []
places = Place.objects.distinct('state')
[place_list.append( Place.objects.filter(state=p.state) ) for p in places]
Is there a better aggregate command I could use for optimizing this? What would be the best way to do this?
~ using Python 2.6, Django 1.3.1
That only hits the database once, rather than once per state like your original version (assuming you use all the results), but you end up with a list of lists instead of a list of querysets.