python - 计算过滤器中的多对多值

标签 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

有没有办法计算多对多对象的数量?

最佳答案

可以通过注解来统计相关对象的个数:

from django.db.models import Count

MyText.objects.filter(
    <b>nauthors=Count('authors')</b>
).filter(<b>nauthors__gte=1</b>)

然而,您在 MyTexts 上过滤至少有一位作者。您可以通过过滤非 NULL 值然后返回一个不同的集合来做到这一点:

MyText.objects.filter(<b>authors__isnull=False</b>)<b>.distinct()</b>

关于python - 计算过滤器中的多对多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738189/

相关文章:

Django jQuery ajax 发布到 https 失败

python - Project Euler #13 理解(Python)

Python MultiProcessing.Pool : How to use with no iterable?

mysql - 几小时不活动后出现 "MySQL server has gone away"错误

python - 登录或匿名用户的 django 单元测试

mysql - laravel 5.4 如何通过用户模型获取当前用户?并且 Auth::user() 不起作用

Python/Django : synonym for field "type" in database model (reserved built-in symbol)

java - MVC : Should this function be in the Controller or in the Model

python - 如何根据 google chrome 检查器提供的信息发出 xml http post 请求

python - DictReader 应该在错误的列数上出错