找到你要的答案

Q:Get latest “group” of objects in queryset

Q:获取最新的“组”对象的查询

I want to get a queryset containing the latest "group" of items (by date). Basically is there a prettier (and more efficent) way of doing this:

# 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)

我想买一包含有最新的“组”的物品(日期)。基本上有一个漂亮的(更有效)的方式来做这件事:

# 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)
answer1: 回答1:

The problem with your code is that it does some work twice and queries twice the db.

What you can do is query once with with select_related (to query only once the published data) and order_by:

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

And then use this queryset to do all your job:

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

你的代码的问题是,它做了一些工作,两次查询的DB。

你能做的是查询一次与select_related(查询只有一次公布的数据)和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
django  django-queryset