Django ORM多表查询
时间: 2023-11-27 15:04:43 浏览: 86
Django ORM多对多查询方法(自定义第三张表&ManyToManyField)
以下是Django ORM多表查询的几个例子:
1. 跨表查询
```python
from app01 import models
# 查询所有出版社及其旗下的书籍
publishers = models.Publisher.objects.all()
for publisher in publishers:
books = publisher.book_set.all()
print(publisher.name, [book.title for book in books])
```
2. join查询
```python
from app01 import models
# 查询所有出版社及其旗下的书籍,使用join查询
publishers = models.Publisher.objects.select_related().all()
for publisher in publishers:
books = publisher.book_set.all()
print(publisher.name, [book.title for book in books])
```
3. 聚合查询
```python
from django.db.models import Count, Avg, Sum, Max, Min
from app01 import models
# 查询每个出版社旗下的书籍数量
publishers = models.Publisher.objects.annotate(book_count=Count('book'))
for publisher in publishers:
print(publisher.name, publisher.book_count)
```
4. 分组查询
```python
from django.db.models import Count, Avg, Sum, Max, Min
from app01 import models
# 查询每个作者出版的书籍数量
authors = models.Author.objects.annotate(book_count=Count('book'))
for author in authors:
print(author.name, author.book_count)
```
阅读全文