我正在开发一个Django应用程序,我遇到了一个棘手的聚合查询,我想评估它。
在我项目的demo
应用程序中,我声明了以下用于表示图书馆馆藏的模型类:
from django.db import models
class Book(models.Model):
interesting = models.BooleanField()
class Library(models.Model):
books = models.ManyToManyField(Book)
我想要查询的是单个图书馆中“有趣”图书的最大数量,这是每个图书馆“有趣”图书的最大数量。
在SQL中,这是:
select max(a.num_interesting_books) as max
from (select count(demo_book.id) as num_interesting_books
from demo_book
inner join demo_library_books on (demo_book.id = demo_library_books.book_id)
where demo_book.interesting=TRUE
group by demo_library_books.library_id) as a
使用以下测试数据:
insert into demo_library(id) values (1), (2), (3);
insert into demo_book(id, interesting) values
(1, FALSE), (2, FALSE), (3, TRUE),
(4, TRUE), (5, TRUE),
(6, TRUE), (7, TRUE), (8, TRUE), (9, FALSE);
insert into demo_library_books(library_id, book_id) values
(1, 1), (1, 2), (1, 3),
(2, 4), (2, 5),
(3, 6), (3, 7), (3, 8), (3, 9), (3, 3);
上述SELECT
语句导致:
max
-----
4
(1 row)
正如所料。
是否可以使用Django的查询API来计算这个值?
答案 0 :(得分:4)
我想我明白了:
Library.objects.filter(books__interesting=True).annotate(num_interesting_books=Count('pk')).aggregate(max=Max('num_interesting_books'))
转换为SQL,这是:
select max(a.num_interesting_books) as max
from (select demo_library.*, count(demo_library.id) as num_interesting_books
from demo_library
inner join demo_library_books on (demo_library.id = demo_library_books.library_id)
inner join demo_book on (demo_library_books.book_id = demo_book.id)
where demo_book.interesting=TRUE
group by demo_library.id) as a