Average of count many to many in django

+1 vote
16 views
asked Mar 14 by anonymous
edited Mar 14

I want to calculate average count in many to many relationship or can say i wanted to calculate the average number of tags per article

e.g.
Article 1 have 10 tags, Article 2 have 5 tags , Article 3 have 0 tags
 
expected output
5

models.py

class Article(models.Model):
    tags = models.ManyToManyField(Tag)
    otherfields

1 Answer

0 votes
answered Mar 14 by anonymous

Simple

Article.objects\
.annotate(num_tags=Count('tags'))\
.aggregate(Avg('num_tags'))
 
{'num_tags__avg': 5}

Welcome , qPocho is an online community for programmers share there knowledge.
...