Hellnar
Hellnar

Reputation: 64793

Django, grouping query items

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

Upvotes: 1

Views: 707

Answers (4)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

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

Upvotes: 2

Bjorn
Bjorn

Reputation: 71820

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.

Upvotes: 1

Mark Lavin
Mark Lavin

Reputation: 25154

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.

Upvotes: 2

brianz
brianz

Reputation: 7418

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.

Upvotes: 3

Related Questions