Take the 2-minute tour ×

say I have such model:

class Foo(models.Model):
 name = models.CharField("name",max_length=25)
 type = models.IntegerField("type number")

after doing some query like Foo.objects.filter(), I want to group the query result as such:

[  [{"name":"jb","type:"whiskey"},{"name":"jack daniels","type:"whiskey"}],
[{"name":"absolute","type:"vodka"},{name:"smirnoff ":"vodka"}],

So as you can see, grouping items as list of dictionaries. List of group query lists intead of dictionary would also be welcome :)


share|improve this question

4 Answers 4

up vote 2 down vote accepted

You can do the grouping in your view by using itertools.groupby().

share|improve this answer

You can do this with the values method of a queryset:



Returns a ValuesQuerySet -- a QuerySet that evaluates to a list of dictionaries instead of model-instance objects.

share|improve this answer

Check out the regroup template tag. If you want to do the grouping for display in your template then this should be what you need. Otherwise you can read the source to see how they accomplish the grouping.

share|improve this answer

You can sort of do this by using order_by:

Foo.objects.order_by( "type" );
drinks = Foo.objects.all( )

Now you have an array of drinks ordered by type. You could use this or write a function to create the structure you want without having to sort it with a linear scan.

share|improve this answer

Your Answer


