Django unification over choice

I have the following model:

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

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

      

Now I have an instance of VotingRound and I would like to know how many times each value has been presented. It's easy to do this with collections. Counter:

>>> Counter(voting_round_instance.vote_set.values_list('vote', flat=True))
Counter({u'decline': 8, u'neutral': 5, u'approve': 4})

      

Now I would like to know if there is a way to do this with Django's aggregate methods ....

I found this module , but before using it, I wanted to know if there is a way to do this.

+3


source to share


1 answer


Yes, you can!

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

      

EDIT: useorder_by()

You may also need to make sure that the default order does not mess up your aggregation. This is especially true when using linked object managers.



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

The fields specified in the order_by () part of the queryset (or used in the default ordering on the model) are used when the output is selected, even if they are not specified otherwise in the values ​​() call. These additional fields are used to group "similar" results together, and they can make otherwise identical rows of results appear to be separate. This manifests itself, in particular, when counting things.

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

      

+4


source







All Articles