如何使用django从每位作者那里获得最新的3本书

时间:2011-04-17 06:16:52

标签: sql django django-queryset

使用以下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查询)来实现这个目的吗?

2 个答案:

答案 0 :(得分:2)

我建议:

for a in Author.objects.all():
    books = a.book_set.all().order_by('-pub_date')[:5]
    print books #and/or process the entries... 

或者,如果订单应始终相同,则定义Meta,

    books = a.book_set.all()[:5]

应该做的伎俩

答案 1 :(得分:1)

如果您担心查询的速度,请在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