whitebear :
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?
Willem Van Onsem :
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()
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=336892&siteId=1