Hi everybody. First post here, beginner. Hope my question is not too dumb.
I have a model ‘StagingMsg’ which contains a manytomany field ‘notices’. I’d like to count how many objects in the model have how many notices, and order them by the latter value (number of notices). So, given the following:
from django.db.models import Count
st = StagingMsg.objects.all()
sx = st.annotate(n_of_notices=Count('notices'))
sx.count()
<275>
sx.filter(n_of_notices=4).count()
<42>
sx.filter(n_of_notices=2).count()
<233>
what I’m looking for is a result
which I can loop through obtaining something like:
n_of_notices: 4, count: 42
n_of_notices: 2, count: 233
What I have tried so far is the following:
result = sx.values('n_of_notices').annotate(count=Count('n_of_notices')).order_by('n_of_notices')
which returns:
FieldError: Cannot compute Count('n_of_notices'): 'n_of_notices' is an aggregate
This one instead doesn’t rise any exception:
result = sx.values('n_of_notices').annotate(count=Count('id')).order_by('n_of_notices')
for res in result:
print(f"n_of_notices: {res['n_of_notices']}, count: {res['count']}")
But it gives:
n_of_notices: 634, count: 634
…not what I was expecting.
Any hint? – Thanks in advance.