django最有效的方法来计算查询中的相同字段值 [英] django most efficient way to count same field values in a query
问题描述
如何有效地计数对象?我想要返回的是:
{'abc':20,'xyz':10,'other':10,000}
或类似的东西,w / o做一吨的SQL调用。
编辑:
我不知道有人会看到这个,因为我正在编辑它迟到了, ...
我有这个模型:
class Action(models。模型):
author = models.CharField(max_length = 255)
purl = models.CharField(max_length = 255,null = True)
,从答案中我已经这样做了:
groups = Action.objects.filter(author = ('purl')。注释(count = Count('purl'))
p>
这是什么组:
{purl:waka} ,{purl:waka},{purl:waka},{purl:waka},{purl:mora},{purl ,{purl:mora},{purl:mora},{purl:mora},{purl:lora}
(我只是用虚拟值填充purl)
我想要的是
{'waka':4,'mora':5,'lora':1}
何仔细看有人会看到这个编辑...
编辑2:
显然我的数据库(BigTable)支持Django的聚合功能,这就是为什么我一直遇到所有问题。
你想要一些类似于count ... 通过...分组。您可以使用django的ORM的聚合功能:
从django.db.models导入计数
fieldname ='myCharField'
MyModel.objects.values(fieldname)
.order_by(fieldname)
.annotate(the_count = Count(fieldname))
有关此主题的以前的问题:
- < a href =https://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django>如何在django中查询为GROUP BY?
- 与GROUP BY相当于COUNT的Django
Lets say if I have a model that has lots of fields, but I only care about a charfield. Lets say that charfield can be anything so I don't know the possible values, but I know that the values frequently overlap. So I could have 20 objects with "abc" and 10 objects with "xyz" or I could have 50 objects with "def" and 80 with "stu" and i have 40000 with no overlap which I really don't care about.
How do I count the objects efficiently? What I would like returned is something like:
{'abc': 20, 'xyz':10, 'other': 10,000}
or something like that, w/o making a ton of SQL calls.
EDIT:
I dont know if anyone will see this since I am editing it kind of late, but...
I have this model:
class Action(models.Model): author = models.CharField(max_length=255) purl = models.CharField(max_length=255, null=True)
and from the answers, I have done this:
groups = Action.objects.filter(author='James').values('purl').annotate(count=Count('purl'))
but...
this is what groups is:
{"purl": "waka"},{"purl": "waka"},{"purl": "waka"},{"purl": "waka"},{"purl": "mora"},{"purl": "mora"},{"purl": "mora"},{"purl": "mora"},{"purl": "mora"},{"purl": "lora"}
(I just filled purl with dummy values)
what I want is
{'waka': 4, 'mora': 5, 'lora': 1}
Hopefully someone will see this edit...
EDIT 2:
Apparently my database (BigTable) does not support the aggregate functions of Django and this is why I have been having all the problems.
You want something similar to "count ... group by". You can do this with the aggregation features of django's ORM:
from django.db.models import Count
fieldname = 'myCharField'
MyModel.objects.values(fieldname)
.order_by(fieldname)
.annotate(the_count=Count(fieldname))
Previous questions on this subject:
这篇关于django最有效的方法来计算查询中的相同字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!