Python 计算过滤器中的多对多值
我正试着这样做 我的班级在这里Python 计算过滤器中的多对多值,python,django,model,Python,Django,Model,我正试着这样做 我的班级在这里 class TweetJson(models.Model): authors = models.ManyToManyField(Station) 和过滤器 MyText.objects.filter(Q(authors__count__gte=1)) 然而,它回来了 Related Field got invalid lookup: count 有什么方法可以计算多对多对象的数量吗?正确的方法是 您需要做的是,首先用作者数对每个TweetJson进
class TweetJson(models.Model):
authors = models.ManyToManyField(Station)
和过滤器
MyText.objects.filter(Q(authors__count__gte=1))
然而,它回来了
Related Field got invalid lookup: count
有什么方法可以计算多对多对象的数量吗?正确的方法是 您需要做的是,首先用作者数对每个
TweetJson
进行注释:
from django.db.models import Count
TweetJson.objects.annotate(num_authors=Count('authors'))
然后,您可以在注释字段上执行\uu gte
查找:
TweetJson.objects.annotate(num_authors=Count('authors')).filter(num_authors__gte=1)
可以通过注释来计算相关对象的数量:
from django.db.models import Count
MyText.objects.filter(
nauthors=Count('authors')
).filter(nauthors__gte=1)
你也可以这样计算:
from django.db.models import Count
MyText.objects.annotate(no_of_authors=Count('authors')).filter(no_of_authors__gte=1)
希望这对您有用。谢谢您的回答和其他方法,我已经尝试了
\uu isnull
,但不知道distinct()
from django.db.models import Count
MyText.objects.annotate(no_of_authors=Count('authors')).filter(no_of_authors__gte=1)