开发者

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


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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜