caliph
caliph

Reputation: 1439

Django: Avg, Max and Min of count of M2M field

I have the models:

class Article(models.Model):
    title = models.TextField(blank=True)
    keywords = models.ManyToManyField(Keyword, null=True, blank=True)

class Keyword(models.Model):
    keyword = models.CharField(max_length=155, blank=True)

I want to calculate the average, minimum and maximum count of M2M relations for all Articles. I am a bit lost here. Can anybody help?

Upvotes: 2

Views: 1839

Answers (1)

vsd
vsd

Reputation: 1473

from django.db.models import Count, Max, Min, Avg

Article.objects.annotate(
    keywords_count=Count('keywords')
).aggregate(
    keywords_count_max=Max('keywords_count'),
    keywords_count_min=Min('keywords_count'),
    keywords_count_avg=Avg('keywords_count')
)
# or
Article.objects.annotate(Count('keywords')).aggregate(
    Max('keywords__count'), Min('keywords__count'), Avg('keywords__count'))

This should return dict {'keywords_count_max': ..., 'keywords_count_min': ..., 'keywords_count_avg': ...} in first case and {'keywords__count__max': ..., 'keywords__count__min': ..., 'keywords__count__avg': ...} in second case. Documentation has example.

Upvotes: 4

Related Questions