【问题标题】:Counting the many-to-many value in filter计算过滤器中的多对多值
【发布时间】:2020-03-18 11:04:27
【问题描述】:

我正在尝试这样做

我的课来了

class TweetJson(models.Model):

    authors = models.ManyToManyField(Station)

和过滤器

MyText.objects.filter(Q(authors__count__gte=1))

但是它会返回。

Related Field got invalid lookup: count

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

【问题讨论】:

    标签: python django model


    【解决方案1】:

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

    from django.db.models import Count
    
    MyText.objects.filter(
        nauthors=Count('authors')
    ).filter(nauthors__gte=1)

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

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

    【讨论】:

    • 感谢您的回答和替代方式,我尝试过__isnull 虽然不知道distinct()
    【解决方案2】:

    正确的做法是shown here

    你需要做的是首先用authors的计数来注释每个TweetJson

    from django.db.models import Count
    TweetJson.objects.annotate(num_authors=Count('authors'))
    

    然后,您可以在注释字段上执行__gte 查找:

    TweetJson.objects.annotate(num_authors=Count('authors')).filter(num_authors__gte=1)
    

    【讨论】:

      【解决方案3】:

      你也可以这样算:

      from django.db.models import Count
      
      
      MyText.objects.annotate(no_of_authors=Count('authors')).filter(no_of_authors__gte=1)
      

      希望这对你有用。

      【讨论】:

        猜你喜欢
        • 2018-02-12
        • 1970-01-01
        • 1970-01-01
        • 2016-01-12
        • 2021-01-13
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        • 2011-01-14
        相关资源
        最近更新 更多