Django Aggregation of values queryset



我有一个名为data的ValuesQuerySet。

我正在尝试获得每个对象的所有类型的摘要计数

data.values('type')产生以下输出:

[{'type': u'internal'}, {'type': u'internal'}, {'type': u'external'}, {'type': u'external'}]

我想得到这样的细分(可以有更多的"内部"one_answers"外部"作为选择。这可能有多达20种不同的类型:

internal: 2
external: 2

我正在尝试,但它只是返回一本空字典。。。

data.values('type').aggregate(Count('type'))

注释也产生了不理想的结果:

data.values('type').annotate(Count('type'))

[{'type': u'internal', 'type_count': 1}, {'type': u'internal', 'type_count': 1}, {'type': u'external', 'type_count': 1}, {'type': u'external', 'type_count': 1}]

型号.py

class Purchase(models.Model):    
    type = models.ForeignKey(Types)
 lists = ModelName.objects.values('type').annotate(count=Count('type'))

在html:中

 {% for list in lists %}
     {{list.type}} - {{list.count}}<br/>
 {% endfor %}

测试:

 {{lists}}
 //don't use forloop yet. This will tests if the above query produce data or it is empty

更新:

def view_name(request):
    lists = ModelName.objects.values_list('type', flat=True).distinct()
    types = []
    for list in lists:
        type_count = ModelName.objects.filter(type=list.type).count()
        types.append({'type': list.type, 'count': type_count})
    return render(request, 'page.html', {
            'types': types,
    })
{% for type in types %}
    {{type.type}} - {{type.count}}
{% endfor %}

它们是几种方法,假设你想在字典中得到结果,简单的方法是:

results = { 'internal': data.filter( value = 'internal'  ).count(),
            'external': data.filter( value = 'external'  ).count() }

对于少数可以使用itertools的查询集,这将工作从数据库层转换到django层。这意味着它只是一个小查询集的解决方案。

from itertools import groupby
results = groupby(data.all(), lambda x: x.type)

最新更新