获取事件列表+模型Django中的计数? [英] Get list of occurrences + count in a model Django?

查看:69
本文介绍了获取事件列表+模型Django中的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有以下模型:

Imagine I have the following model:

class Person(models.Model):
    ...other stuff...
    optional_first_name= models.CharField(max_length=50, blank=True)

如何编写一个请求,以递减的顺序返回最流行的名称数组及其计数,而忽略空名称?

How would I go about writing a request that returns an array of the most popular names, in decreasing order of occurence, with their counts, while ignoring the empty names?

即对于具有13个Leslies,8个Andys,4月3日,1个Ron和18个尚未指定名字的人的数据库,输出为:

i.e. for a database with 13 Leslies, 8 Andys, 3 Aprils, 1 Ron and 18 people who haven't specified their name, the output would be:

[('leslie ',13),('andy',8),('april',3),('ron',1)]

[('leslie', 13), ('andy', 8), ('april', 3), ('ron', 1)]

我能得到的最接近的是通过执行以下操作:

The closest I can get is by doing the following:

q= Person.objects.all()
q.query.group_by=['optional_first_name']
q.query.add_count_column()
q.values_list('optional_first_name', flat= True)

但是仍然不是我想要的。

But it's still not quite what I want.

推荐答案

经过一番挖掘,终于找到了:

After some digging, finally found out:

Person.objects.values('optional_first_name').annotate(c=Count('optional_first_name')).order_by('-c')

这篇关于获取事件列表+模型Django中的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆