获取查询集中对象的最新"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

最新更新