【问题标题】:How to filter objects by number of ForeignKey objects WITHOUT using raw SQL?如何在不使用原始 SQL 的情况下按 ForeignKey 对象的数量过滤对象?
【发布时间】:2012-02-02 16:55:32
【问题描述】:

这在 Django 中终于可以实现了吗?没有这个特性,使用 ORM 有点奇怪。

【问题讨论】:

  • 搜索是一个很好的起点。我想这个问题已经被问过不止一次了。
  • 而且(我看到的)每个答案都涉及原始 SQL。
  • 在我回答之后自然... 几乎重复了stackoverflow.com/questions/1889176/…

标签: python django orm django-aggregation


【解决方案1】:

实际上,Django 聚合文档中有两个部分,称为 filtering on annotationsorder_by(),它们应该可以满足您的需求:

books_w_author_count = Book.objects.annotate(num_authors=Count('authors'))

# just a filter by number of objects
books_w_author_count.filter(num_authors__gt=1)

# just ordering on the count
books_w_author_count.order_by('num_authors')

class Author(modules.Model):
   # ...

class Book(models.Model):
   # ...
   authors = models.ManyToManyField(Author)

【讨论】:

    【解决方案2】:

    您可以通过使用注释功能来做到这一点。 Here你可以找到例子

    还有文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2018-08-22
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多