我正在尝试为每个作者提取最新的3本书,使用DateField作为日期。 有任何想法如何使用Django ORM或原始SQL?
class Author(models.Model):
name = models.CharField('Name', max_length=100)
slug = models.SlugField('Slug', max_length=100, unique=True)
class Book(models.Model):
author = models.ForeignKey(Author, verbose_name='Author')
published = models.DateField('Published on', db_index=True)
答案 0 :(得分:0)
您可以遍历所有作者,为每个作者选择3本最新书籍并将其添加到全局列表中:
books = []
for x in Author.objects.all():
bookslist = Book.objects.filter(author=x).order_by('-published')[:3]
for book in bookslist:
books.append(book)