V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
stage37
V2EX  ›  Python

求解一个 Django ORM 相关的优化问题

  •  
  •   stage37 · 2015-09-07 19:32:48 +08:00 · 2412 次点击
    这是一个创建于 3125 天前的主题,其中的信息可能已经有所发展或是发生改变。

    先上代码:

    models.py

    class TypeA (models.Model ):
        ...
        @property
        def field (self ):
            if self.typeb_set.count ():
                return self.typeb_set
        ...

    class TypeB (models.Model ):
        ...
        typea = models.ForeignKey (TypeA )
        ...

    其中 TypeA 和 TypeB 是一对多的关系。

    templates/some_page.html

    {% for item in items %}
      {% for obj in item.obj_list %} {# 此处的 obj 与 models.py 中的 TypeA 对应 #}
      <ol>
        <li>{ obj.f1 }</li>
        <li>{ obj.f2 }</li>
        <li>{ obj.f3 }</li>
        <li>{ obj.field }</li>
      </ol>
      {% endfor %}
    {% endfor %}

    每次执行到{{ obj.field }}时都会查询一次 TypeB 对应的表,现在如果 obj 的个数非常多就会有很多次查询,严重影响页面加载速度。

    查了下似乎 prefetch_related ()和 select_related ()跟这个问题相关,但是手册里介绍的跟上面这种情况有略有区别。

    请问有什么优化的方法吗?

    3 条回复    2015-09-08 21:58:25 +08:00
    ljdawn
        1
    ljdawn  
       2015-09-07 20:18:10 +08:00
    就是用 related 呀
    facert
        2
    facert  
       2015-09-08 12:23:06 +08:00
    foreignkey 用 select_related
    stage37
        3
    stage37  
    OP
       2015-09-08 21:58:25 +08:00
    @facert 搞定了,最后用的 prefetch_related ()。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3223 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 13:53 · PVG 21:53 · LAX 06:53 · JFK 09:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.