Django 聚合选择

标签 django django-aggregation

我有以下模型:

class VotingRound(models.Model):
     pass # here are some unimportant fields

class Vote(models.Model):
     voting_round = models.ForeignKey(VotingRound)
     vote = models.CharField(choices=...)

现在我有 VotingRound 的实例,我想知道每个值代表了多少次。这可以通过 collections.Counter 轻松完成:
>>> Counter(voting_round_instance.vote_set.values_list('vote', flat=True))
Counter({u'decline': 8, u'neutral': 5, u'approve': 4})

现在我想知道是否有办法使用 Django 聚合技术来做到这一点....

我找到了 this module ,但在使用它之前我想知道是否有本地方式来做到这一点。

最佳答案

是的你可以!

from django.db.models import Count
voting_round_instance.vote_set.values('vote') \
    .annotate(count=Count('vote')).distinct()

编辑:使用 order_by()
您可能还需要确保默认排序不会弄乱您的聚合。在使用相关对象管理器时尤其如此。

https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

Fields that are mentioned in the order_by() part of a queryset (or which are used in the default ordering on a model) are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. This shows up, particularly, when counting things.


from django.db.models import Count
voting_round_instance.vote_set.values('vote') \
    .annotate(count=Count('vote')) \
    .distinct().order_by()

关于Django 聚合选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836920/

相关文章:

python - 在 Django 中更改模型会导致数据库损坏?

Django:如何测试RelatedManager的类型?

python - Django 注释外键的外键计数

Django : Count only non-empty CharField with annotate() & values()

javascript - 无法与 websocket 通信。高速公路 : received HELLO message, 且 session 尚未建立

python - 是否有积极开发的 Django/Python 工作流框架?

mysql - 在 WebFaction 中使用 Django 和 MySQL

python - F 表达式列表的求和

python - 使用 Django,我如何在单个查询中实现此目的?

mysql - Django 1.6 + MySQL : Type Cast MySQL variable to search for Max, 平均