gpt4 book ai didi

database - 如何使用 Django 执行 SQL LEFT JOIN?

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:26 29 4
gpt4 key购买 nike

基本上我需要对每个条目的评论进行计数:

SELECT e.*, COUNT(c.id) as comments FROM blog_entry e LEFT JOIN blog_comment c ON e.id = c.entry_id GROUP BY e.id, e.name, e.name_slug, e.date_published, e.category, e.image, e.body, e.is_published, e.views, e.subscription_sent ORDER BY e.date_published DESC LIMIT 15;

但我不知道如何使用 Django 来解决这个问题。

这是我目前所拥有的,它运行完美,除了没有评论计数。有人可以指出使用 Django 进行这样的连接的正确方向吗?

from project.blog.models import Entry, Comment

def index(request):
latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:15]
return render_to_response('blog/index.html', {'latest_entry_list': latest_entry_list)

最佳答案

django 1.1 支持聚合查询,你可以通过 svn trunk 获取最新版本。文档已经更新

http://docs.djangoproject.com/en/dev/topics/db/aggregation/

关于database - 如何使用 Django 执行 SQL LEFT JOIN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/450729/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com