[英]How to get the latest 3 books from each author using django
使用以下django模型:
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
author = models.ForeignKey(Author)
pubdate = models.DateField()
class Meta:
ordering = ('-pubdate')
我如何獲得每位作者出版的五本最新書籍 ?
我考慮過迭代每個作者,並得到該作者出版的書籍,分為5部分。
for a in Author.objects.all():
books = Book.objects.filter(author = a )[:5]
print books #and/or process the entries...
但是,如果表中有很多記錄(也許是數千本書),則可能會很慢且效率低下。
那么,還有其他方法可以通過django(或sql查詢)完成此操作嗎?
我會建議 :
for a in Author.objects.all():
books = a.book_set.all().order_by('-pub_date')[:5]
print books #and/or process the entries...
或者,如果順序應始終相同,則在您定義元時,
books = a.book_set.all()[:5]
應該可以
如果您擔心查詢的速度,請在pubdate字段上建立索引:
pubdate = models.DateField(db_index=True)
這應該避免每次運行查詢時都掃描整個表。
在postgres中,SQL類似於:
select b1.name, b1.author
from books b1
where b1.id in (
select b2.id
from books b2
where b1.author = b2.author
order by b2.pubdate desc
limit 3)
order by b1.author, b1.name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.