Django 模型:使用唯一外键从 table 获取结果

Django Model: Getting result from a table using unique foreign key

我有两个模型是这样的:

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

您需要 annotate 对您的查询集进行大量聚合(参考:Aggregation [Django Docs]). To get the counts you can use the Count [Django Docs] function and for the last_created / last_modified you can use the 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)