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
pc10201
V2EX  ›  Python

如何绕过 django 的惰性查询(lazy query)机制?

  •  
  •   pc10201 · 2015-08-06 16:56:08 +08:00 · 3380 次点击
    这是一个创建于 3186 天前的主题,其中的信息可能已经有所发展或是发生改变。
    楼主数据库中有一个表,三千多条数据,想一次性输出到一个html页面中

    先获取到结果集,然后在模板中for循环渲染

    django默认是使用了惰性查询(lazy query)

    然后发现一下子有三千多条查询语句。

    能否一次性读到内存中,绕过这个惰性查询?
    8 条回复    2015-09-05 11:14:04 +08:00
    PanJiaChen
        1
    PanJiaChen  
       2015-08-06 17:06:03 +08:00
    我不会
    Sinic
        2
    Sinic  
       2015-08-06 18:21:31 +08:00
    你是不是用了queryset.iterator()?使用iterator()无法生成cache,遍历同一个queryset时会重复执行查询。
    virusdefender
        3
    virusdefender  
       2015-08-06 19:27:11 +08:00
    逆循环的时候是不是涉及到每一项的外键的内容了?

    如果是这样的话,一次查出来就好了。https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-related
    onlyice
        4
    onlyice  
       2015-08-06 19:29:11 +08:00
    猜测跟 Django 的 lazy query 没有关系。。
    可能是你的 Model 有 Relation,用 prefetch_related 试试
    zhuangzhuang1988
        5
    zhuangzhuang1988  
       2015-08-06 22:56:34 +08:00
    贴关键代码, Django应该也不会3000条就生成出3000个查询语句的
    tudou527
        6
    tudou527  
       2015-08-07 09:27:52 +08:00
    同问,肯定是楼主代码的问题。
    pc10201
        7
    pc10201  
    OP
       2015-08-07 10:18:07 +08:00
    @zhuangzhuang1988
    关键代码:
    视图中的
    items = Exams.objects.raw("""
    SELECT * from exams,vendor
    WHERE exams.vendor_id=vendor.id
    ORDER BY vendor.name asc,exams.`code` ASC""")
    exams

    模板中的
    {% for item in items %}
    <tr>
    <th scope="row">{{ forloop.counter }}</th>
    <td><a href="{% url 'exam' item.code %}">{{ item.code }}</a></td>
    <td>{{ item.vendor.name }}</td>
    <td>{{ item.name }}</td>
    </tr>
    {% endfor %}

    Exams表中的vendor是外键,关联vendor表
    pc10201
        8
    pc10201  
    OP
       2015-09-05 11:14:04 +08:00
    @virusdefender 是的,我用了 select-related ,大幅度提高了性能哈
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1165 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:21 · PVG 02:21 · LAX 11:21 · JFK 14:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.