避免n + 1个查询来查询模型以及所有ForeignKey关联? [英] Avoiding n+1 queries to query model plus all ForeignKey associations?

查看:105
本文介绍了避免n + 1个查询来查询模型以及所有ForeignKey关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:称他们为问题和答案:

I have two models: call them questions and answers:

class FacetQuestion(models.Model):
    the_question    = models.CharField(max_length=50)

class FacetAnswer(models.Model):
    question        = models.ForeignKey(FacetQuestion)
    display_order   = models.SmallIntegerField()
    the_answer      = models.CharField(max_length=1024)

我想展示所有问题和答案列在一个列表中,并按我的选择排序问题和答案:

I'd like to present all the questions and answers in one list, with the questions and answers ordered per my choosing:

Q1
  A1
  A2
  A3
Q2
  A10
  A9
  A4

无需创建n + 1个数据库查询或创建外观愚蠢的模板。
对于像我这样的数据库专家来说,这很容易,但是Toto告诉我们我们已经不在SQL领域了:

Without creating n+1 database queries or creating silly looking templates. That's an easy join for a database guy like myself, but Toto informs us we're not in SQL land anymore:

select title_short,answer_note from coat_facetquestion
join coat_facetanswer on (coat_facetanswer.question_id=coat_facetquestion.id)
order by coat_facetquestion.id,coat_facetanswer.display_order;

Django中最好的方法是什么,模板是什么样?

What's the best way in Django, and what would the template look like?

<ul>
    {% for q in questions %}
    <li>{{ q.the_question }}</li>
        {% for a in q.FacetAnswers_set.all %}
            <li>{{ q.the_answer }}</li>
        {% endfor %}
    {% endfor %}
</ul>

我看到了一个较旧的模块,该模块在 django-batch-select 。还有 select_related()似乎一定是答案,但是如果是这样的话,说明文档还不太清楚。

I see an older module that's a bit on track at django-batch-select. There's also select_related() which feels like it must be the answer, but if so the documentation is not quite making that clear.

推荐答案

基于搜索其他堆栈交换答案:对于处理分层数据,最好的解决方法是 http://django-mptt.github.com/django-mptt/

Based on searching other stack exchange answers: for dealing with the hierarchical data, the best seems to be http://django-mptt.github.com/django-mptt/

仅用于减少查询数量 select_related()是一个很好的帮助。

For simply reducing the number of queries select_related() is a great help.

对于显示分层结果,我还没有发现太多。

For displaying the hierarchical result I have not yet found much.

这篇关于避免n + 1个查询来查询模型以及所有ForeignKey关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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