推荐学习书目
› 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 · Sep 7, 2015 · 3581 views
    This topic created in 4039 days ago, the information mentioned may be changed or developed.

    先上代码:

    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 replies  •  2015-09-08 21:58:25 +08:00
    ljdawn
        1
    ljdawn  
       Sep 7, 2015
    就是用 related 呀
    facert
        2
    facert  
       Sep 8, 2015
    foreignkey 用 select_related
    stage37
        3
    stage37  
    OP
       Sep 8, 2015
    @facert 搞定了,最后用的 prefetch_related ()。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5133 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:35 · PVG 14:35 · LAX 23:35 · JFK 02:35
    ♥ Do have faith in what you're doing.