Reputation: 64883
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: 711
Reputation: 799520
You can do the grouping in your view by using itertools.groupby()
.
Upvotes: 2
Reputation: 71970
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
Reputation: 25164
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
Reputation: 7448
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