Django:使用 Django ORM 实现 JOIN? [英] Django: implementing JOIN using Django ORM?

查看:58
本文介绍了Django:使用 Django ORM 实现 JOIN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 Django 构建的 Q&A 类型的网站,具有以下模型:

I have a Q&A type of site built in Django with the following models:

class Question(models.Model):
    title = models.CharField(max_length=70)
    details = models.TextField()

class Answer(models.Model):
    question_id = IntegerField()
    details = models.TextField()

我需要显示一个特定的问题及其答案.通常我需要 2 个查询才能做到这一点:

I need to display a specific question together with its answers. Normally I'd need 2 queries to do that:

Question.objects.get(id=1)
Answer.objects.get(question_id=1)[:10]

我希望使用一个查询来检索所有内容.在 MySQL 中它会是:

I'm hoping to retrieve everything using one query. In MySQL it'd be:

SELECT *
FROM Question JOIN Answer ON Question.id=Answer.question_id
WHERE Question.id=1
LIMIT 10

无论如何我可以通过 Django 的 ORM 做到这一点吗?extra() 在这种情况下会有帮助吗?

Is there anyway I could do this through Django's ORM? Would extra() help in this case?

推荐答案

这正是 select_related() 确实如此.唯一的问题是你必须从答案模型开始,而不是问题,但是结果是一样的:

This is exactly what select_related() does. The only gotcha is that you have to start with the Answer model, rather than Question, but the result is the same:

answers = Answer.objects.filter(question_id=1).select_related() 

现在每个答案对象都有一个预取的问题"属性,并且访问它不会再次命中数据库.

Now each answer object has a pre-fetched 'question' attribute, and accessing it won't hit the db again.

这篇关于Django:使用 Django ORM 实现 JOIN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆