sql - Django 模型:使用唯一外键从表中获取结果
问题描述
我有两个看起来像这样的模型:
class Author(models.Model):
name = models.CharField(max_length=200)
class Book(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
isbn_id = models.CharField(max_length=50, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
我怎样才能进行这样的查询:
我得到每个作者创建的书籍总数,带有 isbn 的书籍数量。
每次为作者创建一本书时,我都可以获得 last_created、last_modified。
这是我试图达到的结果的一个例子;
s/n| author| no_books_with_isbn| all_books| last_created| last_modified
1. Faye 2 2 ... ....
2. Soya 2 5
3. Jake 6 6
4. Gurj 4 4
5. Zoom 2 10
解决方案
您需要对查询集进行annotate
大量聚合(参考:聚合 [Django Docs])。要获得计数,您可以使用Count
[Django Docs]函数,对于 last_created / last_modified 您可以使用Max
[Django Docs]函数来实现您想要的:
from django.db.models import Count, Max, Q
queryset = Author.objects.annotate(
all_books=Count('book'),
no_books_with_isbn=Count(
'book',
filter=Q(book__isbn_id__isnull=False)
),
last_created=Max('book_created_at'),
last_modified=Max('book_updated_at')
)
for author in queryset:
print(author.name, author.no_books_with_isbn, author.all_books, author.last_created, author.last_modified)
推荐阅读
- loops - E0597 试图循环一个向量
- webhooks - Spinnaker webhook 阶段不允许超过 5 分钟的超时
- azure - 我可以使用 RBAC 访问 Azure 服务总线中继吗?
- python - 解析时间数据并格式化输出
- mirth - Mirth - EDI/X12 到 EDI/X12 - 只想更改分隔符
- sql - MS Access:玩日期
- javascript - 用于创建 (p5.js) 主体的 for 循环
- go - 如何在 vim 中显示从 go(lang) 包中导入的可能函数/变量
- python - 如何为熊猫布尔掩码中的每个连续真值序列分配唯一的分组值
- python - 将列表名称创建为字符串后如何打印列表?