我想获得一个包含最新“组”项目的查询集(按日期)。基本上有一种更漂亮(更有效)的方式:
# 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)
答案 0 :(得分:0)
您的代码存在的问题是,它会执行两次操作并查询数据库的两倍。
您可以使用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