这在 Django 中终于可能了吗?如果没有这个功能,使用 ORM 就会有点奇怪。
最佳答案
Django 聚合文档中实际上有两个部分,名为 filtering on annotations和 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)
关于python - 如何在不使用原始 SQL 的情况下按foreignkey对象的数量过滤对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9116424/