首页 > 解决方案 > 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)

我怎样才能进行这样的查询:

  1. 我得到每个作者创建的书籍总数,带有 isbn 的书籍数量。

  2. 每次为作者创建一本书时,我都可以获得 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

标签: sqldjangodjango-modelsdjango-queryset

解决方案


您需要对查询集进行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)

推荐阅读