【发布时间】:2017-03-03 16:44:38
【问题描述】:
我需要选择匹配特定模式的条目,计算它们并选择最新的。如何通过 Django ORM 做到这一点?
试过了:
Entry.objects.filter(A=B).annotate(Count("something")).latest("date")
每个 B 只计算 1 项。如果我删除 latest("date"),它会正确计数,但只给出计数,没有其他内容。如何正确执行此任务?
UPD:实际代码
def render_entries(request):
ids = Entry.objects.values("entry_token").distinct()
entries = [Entry.objects.filter(entry_token=x["entry_token"]).annotate(count=Count("id")).latest("date_time") for x in ids]
return render(request, "entries_list.html", {'entries':entries})
【问题讨论】:
-
为什么不把它分成两句话呢?
-
听起来像是两个不同的查询
-
UPD:您的代码看起来像反模式示例。
-
@danihp 感谢您的观察,帮助很大!
-
那么如果你这样做了
entries = [Entry.objects.filter(entry_token=x["entry_token"]).annotate(count=Count("id")).order_by("-date_time").first() for x in ids]
标签: django python-3.x django-orm