【问题标题】:How to get the latest 3 books from each author using django如何使用 django 从每个作者那里获取最新的 3 本书
【发布时间】:2011-08-07 04:58:48
【问题描述】:

使用以下 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 查询)来完成此任务?

【问题讨论】:

    标签: sql django django-queryset


    【解决方案1】:

    我建议:

    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]
    

    应该做的伎俩

    【讨论】:

    • 这会让你得到 n 个查询。使用 SQL 会好很多。
    【解决方案2】:

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

    【讨论】:

    • 我用的是 mysql,这个版本的 MySQL 还不支持 'LIMIT & IN/ALL/ANY/SOME 子查询'
    • 我不会担心用 SQL 编写查询。使用大表,您将看到仅构建索引的最大好处。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多