选择上的Django聚合
我有以下型号:选择上的Django聚合,django,django-aggregation,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的实例,我想知道每个值代表了多少次。这可以通过集合轻松
class VotingRound(models.Model):
pass # here are some unimportant fields
class Vote(models.Model):
voting_round = models.ForeignKey(VotingRound)
vote = models.CharField(choices=...)
现在我有了VotingRound的实例,我想知道每个值代表了多少次。这可以通过集合轻松完成。计数器:
>>> Counter(voting_round_instance.vote_set.values_list('vote', flat=True))
Counter({u'decline': 8, u'neutral': 5, u'approve': 4})
现在我想知道是否有一种方法可以通过Django聚合技术实现这一点
我已经找到了,但在使用它之前,我想知道是否有本地的方法可以做到这一点。是的,你可以
from django.db.models import Count
voting_round_instance.vote_set.values('vote') \
.annotate(count=Count('vote')).distinct()
编辑:使用order\u by()
您可能还需要确保默认顺序不会扰乱聚合。使用相关对象管理器时尤其如此
查询集的order_by()部分中提到的字段(或在模型的默认排序中使用的字段)在选择输出数据时使用,即使在values()调用中没有另行指定。这些额外字段用于将“相似”结果分组在一起,它们可以使其他相同的结果行看起来是分开的。尤其是在数东西的时候
我已经尝试过了,但它给了我这样一个信息:我还应该注意,我正在使用django 1.8。。。在这里查看完整模型很可能是因为您使用的是相关的对象管理器;这将只需要筛选相关行<代码>排序依据(‘投票’)应该有效。
from django.db.models import Count
voting_round_instance.vote_set.values('vote') \
.annotate(count=Count('vote')) \
.distinct().order_by()