counting and aggregating manytomany field objects in model

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.

Welcome @frnc !

Please post your StagingMsg model. Additionally, if notices is a reverse-FK reference to another model, please post that other model as well.

Hi Ken,

thank you very much for your reply. Here are the two models (StagingMsg is a subclass of Message because I have other children FOOMsg models that must contain other types of messages in different tables):

class Notice(models.Model):
    # notices retrieved from source 
    number = models.CharField(max_length=30, primary_key=True)
    pub_date = models.DateTimeField("date published")
    cpv = models.CharField(max_length=15)
    title = models.TextField()
    [...]  # other not relevant fields 

class Message(models.Model):
    [...]  # some not relevant fields
    recipient = models.ForeignKey(Recipient, on_delete=models.CASCADE)
    composition_date = models.DateTimeField("date composed")
    notices = models.ManyToManyField(Notice, verbose_name="list of notices")
    sent = models.BooleanField(default=False)

class StagingMsg(Message):
    # whether it has a yet unseen notice
    has_unseen = models.BooleanField(default=False)

Thanks.