我正在尝试这样做
我的课来了
class TweetJson(models.Model):
authors = models.ManyToManyField(Station)
和过滤
MyText.objects.filter(Q(authors__count__gte=1))
但是它会返回。
Related Field got invalid lookup: count
有没有办法计算多对多对象的数量?
最佳答案
可以通过注解来统计相关对象的个数:
from django.db.models import Count
MyText.objects.filter(
<b>nauthors=Count('authors')</b>
).filter(<b>nauthors__gte=1</b>)
然而,您在 MyText
s 上过滤至少有一位作者。您可以通过过滤非 NULL
值然后返回一个不同的集合来做到这一点:
MyText.objects.filter(<b>authors__isnull=False</b>)<b>.distinct()</b>
关于python - 计算过滤器中的多对多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738189/