如何创建一个查询?

How create one query?

一个作者有很多书。数据库中有许多作者的书籍。 需要获得作者的最新书籍。在一个查询中。

class Autor(models.Model):
    name = models.Charfield()


class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query

获取该作者的所有书籍,降序排列取第一条记录

latest_books = []
for author in Author.objects.all():
    last_book = Books.objects.filter(author=author).order_by("-created_at")[0]
    latest_books.append(last_book)

您可以简单地使用 Subquery:

from django.db.models import Subquery, OuterRef

books = Book.objects.filter(author=OuterRef('pk'))
authors = Author.objects.annotate(book=Subquery(books.order_by('-created').values('name')[:1]))

这将在一个查询中得到答案。按作者对书籍进行分组,并获取每组的最新 created_date。过滤匹配 latest_dates

中创建日期的记录
qs = Book.objects.all()
latest_dates = qs.values('author').annotate(latest_created_at=Max('created_at'))
qs = qs.filter(created_at__in=latest_dates.values('latest_created_at')).order_by('-created_at')