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

查看:683
本文介绍了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()

我需要一起显示一个特定的问题与答案。通常我需要两个查询:

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() 

现在每个答案对象都有一个预先提取的问题属性,而
访问它不会再次击中db。

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天全站免登陆