whitebear
whitebear

Reputation: 12423

Counting the many-to-many value in filter

I am trying to do like this

my class is here

class TweetJson(models.Model):

    authors = models.ManyToManyField(Station)

and filter

MyText.objects.filter(Q(authors__count__gte=1))

However it returns.

Related Field got invalid lookup: count

is there any way to count the number of many-to-many objects?

Upvotes: 3

Views: 185

Answers (3)

Rahul Kumar
Rahul Kumar

Reputation: 19

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.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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()

Upvotes: 3

AKS
AKS

Reputation: 19801

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)

Upvotes: 3

Related Questions