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

标签 database django performance postgresql

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

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/

相关文章:

database - 无法手动将数据保存在Grails中的数据库中,但是使用dbconsole可以很好地工作

java - 使用从 MySQL 数据库读取列名的方法返回的数组已满 "null"

plugins - jQuery 延迟加载是否有任何真正的性能提升?

performance - 如何高效地从两个表中选择数据?

ruby-on-rails - 奇怪的迁移错误

php - 如何操作多维数组

python - 制定通用模型保存方法

python - 多个子域的 Django 多 session cookie 域

python - 为 Django 应用程序创建 REST API

performance - 在Powershell脚本或命令行中创建和编辑性能计数器