Reputation: 12423
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
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
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 MyText
s 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
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