Django N + 1查询解决方案 [英] Django N+1 query solution

查看:153
本文介绍了Django N + 1查询解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与...通话后访问了 http://guides.rubyonrails.org/active_record_querying.html 一个关于N + 1的对等体以及糟糕的DB查询的严重性能影响。

I visited http://guides.rubyonrails.org/active_record_querying.html after talking with a peer regarding N+1 and the serious performance implications of bad DB queries.

ActiveRecord(Rails):

ActiveRecord (Rails):

clients = Client.includes(:address).limit(10)



客户端有地址,我打算通过客户端循环访问它们时,Rails提供包括,让它知道,并将它们添加到查询中,它消除了蝙蝠之外的9个查询。

Where client's have addresses, and I intend to access them while looping through the clients, Rails provides includes to let it know to go ahead and add them to the query, which eliminates 9 queries right off the bat.

Django:

https://github.com/lilspikey/django-batch-select 提供批量查询支持。你知道其他图书馆或技巧来实现Rails在上面提供的内容,但是在一个不太详细的庄园里(就像在19个字符修正了N + 1而非常清楚的rails示例)?另外,批次选择以同样的方式解决问题,还是这两个不同的东西?

https://github.com/lilspikey/django-batch-select provides batch query support. Do you know of other libraries or tricks to achieve what Rails provides above, but in a less verbose manor (as in the rails example wherein just 19 chars fix N+1 and is very clear)? Also, does batch-select address the concern in the same way, or are these two different things?

BTW,我不是问 select_related ,尽管它似乎是乍一看的答案。我在谈论一个情况,其中地址有一个forign键到客户端

BTW, I'm not asking about select_related, though it may seem to be the answer at first glance. I'm speaking of a situation where address has a forign key to client.

推荐答案

可以使用prefetch_related自Django 1.4:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

You can do it with prefetch_related since Django 1.4: https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

如果您使用< 1.4,看看这个模块:
https://github.com/ionelmc/django-prefetch

If you're using < 1.4, have a look at this module: https://github.com/ionelmc/django-prefetch

它声称比Django的prefetch_related更灵活。详细但是很棒。

It claims to be more flexible than Django's prefetch_related. Verbose but works great.

这篇关于Django N + 1查询解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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