2

这在 Django 中最终可能吗?没有这个特性,使用 ORM 有点奇怪。

4

2 回答 2

2

Django 聚合文档中实际上有两个部分称为“注解过滤”order_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)
于 2012-02-02T17:06:32.660 回答
1

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

和文档在这里

于 2012-02-02T17:05:41.600 回答