开发者

Counting database entries by field type in django

I have a model in my django project called "change" and it 开发者_运维技巧has a field called "change_type". There are multiple values within the change_type field to include "move", "new", "edit" and others with new types being added randomly over any given period of time. I am currently using normal django queries to select groups of entries within the change model.

Is there a quick method to determine what unique entries are in the change_type field? Is there a quick method to return a count of each entry type?


After finding the solution, it is really simple.

Change.objects.all().values('change_type').distinct()


Putting it together:

 occurrences = {}
 change_types = Change.objects.values_list('change_type', flat=True).distinct()

 for type in change_types:
     occurrences[type] = Change.objects.filter(change_type=type).count()


http://docs.djangoproject.com/en/dev/topics/db/managers/ maybe that will be helpful for You.


This can now be much more effectively implemented using aggregation:

Change.objects.values('change_type').annotate(Count('change_‌​type'))

The output contain change_type__count field for each respective change_type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜