一个作者有很多书。数据库中有很多作者都有书籍。 需要获得作者的最新书籍。在一个查询中。
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
答案 0 :(得分:3)
您可以简单地使用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]))
答案 1 :(得分: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')
答案 2 :(得分:-1)
获取作者的所有书籍,按降序排列并获取第一条记录
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)