获取查询集中最新的 "group" 个对象

Get latest "group" of objects in queryset

我想获取包含最新 "group" 项(按日期)的查询集。基本上有没有更漂亮(更有效)的方法来做到这一点:

# get the latest set of news. It may or may not be today. 
# TODO: this seems ugly, find a better way
latest = Article.objects.latest('published')
latest_items = Article.objects.filter(published__year=latest.published.year,
                                                 published__month=latest.published.month,
                                                 published__day=latest.published.day)

您的代码的问题在于它做了两次工作并查询了两次数据库。

你可以做的是用 select_related 查询一次(只查询一次 published 数据)和 order_by:

articles = Article.objects.select_related('published').order_by('published')

然后使用此查询集完成您的所有工作:

def getLatest(queryset):
    latest = queryset.first()
    if latest == None:
        return

    for obj in queryset:
        if obj.published__year == latest.published__year and obj.published__month == latest.published__month and obj.published__day == latest.published__day:
            yield obj
        else:
            return