【问题标题】:How to count number of entries, annotate it and select latest with Django ORM如何计算条目数,对其进行注释并使用 Django ORM 选择最新的
【发布时间】: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


【解决方案1】:

已更新可能不是最理想的,但这应该可以。

def render_entries(request):
    # get list of all entry_tokens with count
    tokens = Entry.objects.values('entry_token').annotate(count=Count('entry_token'))
    # create list of entries
    entries = []
    for token in tokens:
        entry = Entry.objects.filter(entry_token=token['entry_token']).latest('date_time')
        entry.count = token['count']
        entries.append(entry)
    return render(request, "entries_list.html", {'entries':entries})

【讨论】:

  • 结果与问题中提供的相同。
  • @wasd 向我们展示您的确切代码。它不可能只返回计数。
  • 它不仅返回计数 - 它只计算 1 项
  • @wasd 啊。了解将 "something" 更改为 "id"。这应该可以解决您的问题。
  • 由于某种原因根本没有变化
猜你喜欢
  • 1970-01-01
  • 2020-06-15
  • 2020-09-09
  • 2019-04-18
  • 2018-08-26
  • 1970-01-01
  • 2015-09-22
  • 2020-10-27
  • 2021-11-15
相关资源
最近更新 更多