views:

163

answers:

4

Hello,

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"}],
[{name:"tuborg","type":beer}]
]

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

Regards

+2  A: 

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

http://docs.djangoproject.com/en/1.1/ref/models/querysets/#values-fields

values(*fields)

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

brianz
+1  A: 

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.

apphacker
+1  A: 

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.

Mark Lavin
+2  A: 

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

Ignacio Vazquez-Abrams