[Django]-Counting the many-to-many value in filter

3👍

You can count the number of related objects by annotating:

from django.db.models import Count

MyText.objects.filter(
    nauthors=Count('authors')
).filter(nauthors__gte=1)

Here you are however filtering on MyTexts with at least one author. You can do that by filtering for non-NULL values and then return a distinct set:

MyText.objects.filter(authors__isnull=False).distinct()

3👍

The proper way to do this is shown here.

What you need to is that first annotate each TweetJson with the count of authors:

from django.db.models import Count
TweetJson.objects.annotate(num_authors=Count('authors'))

And, after this you can perform the __gte lookup on annotated field:

TweetJson.objects.annotate(num_authors=Count('authors')).filter(num_authors__gte=1)
👤AKS

2👍

you can count like this also:

from django.db.models import Count


MyText.objects.annotate(no_of_authors=Count('authors')).filter(no_of_authors__gte=1)

Hope this will work for you.

Leave a comment