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

询问一个关于 Django 查询方面的问题,请赐教

  •  
  •   hao1032 · 2016-07-21 15:17:49 +08:00 · 2571 次点击
    这是一个创建于 2837 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Car(models.Model):
    type = models.CharField(max_length=20) # 可能的值 出租车,卡车,轿车

    假设我有上面这个 model ,表里面有 30000 条数据,出租车,卡车,轿车各不少于 1000 条。

    我现在有一个需求查询出租车,卡车,轿车各 100 条数据,我现在的做法是使用 3 个查询,如下:
    q = Car.objects
    cz = q.filter(type='出租车')[: 100]
    kc = q.filter(type='卡车')[: 100]
    jc = q.filter(type='轿车')[: 100]

    以上是举例,实际 type 有 20 多个,这种单个查询影响了效率。

    请问大神, Django 中有没有办法经过一次查询操作,就能满足上述需求呢?
    需求:一次查询的结果中包含多个 type ,每个 type 有 100 个结果。
    10 条回复    2016-07-22 14:10:48 +08:00
    28ms
        1
    28ms  
       2016-07-21 16:06:51 +08:00
    用 raw sql 查比较方便
    stargazer
        2
    stargazer  
       2016-07-21 18:10:51 +08:00
    raw +1
    petelin
        3
    petelin  
       2016-07-21 18:33:00 +08:00 via Android
    raw+1 有些东西真的不能一次搞出来,必须得自己写
    hao1032
        4
    hao1032  
    OP
       2016-07-21 22:45:16 +08:00
    @28ms @petelin @petelin 大家说的 raw 指的是用 union all 吗?
    petelin
        5
    petelin  
       2016-07-21 23:04:08 +08:00 via Android
    @hao1032 应该是直接拼接 sql 语句吧,这个有点类似于分组取每组 top100
    Allianzcortex
        6
    Allianzcortex  
       2016-07-22 08:58:04 +08:00
    我也感觉直接拼, 上原生 sql,Google 上搜“ django model select different type ”没有什么太好的结果
    wph95
        7
    wph95  
       2016-07-22 10:14:25 +08:00
    types = [car, taxx ...]
    cars = Car.objects.filter(types_in=types)
    dict = {}
    for type in types:
    dict[type] = []
    for car in cars:
    dict[car.type].append(car)
    glasslion
        8
    glasslion  
       2016-07-22 10:20:46 +08:00
    @hao1032 mysql 以外的的 RDMS 可以用 window function
    hao1032
        9
    hao1032  
    OP
       2016-07-22 14:09:02 +08:00
    @wph95 项目有 12w 数据且分布不定。这样的的做法效率也不高。
    hao1032
        10
    hao1032  
    OP
       2016-07-22 14:10:48 +08:00
    All 感谢大家的回复,最终决定新建立一个表,里面只保存各 type 最近的 100 个结果。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5631 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:39 · PVG 14:39 · LAX 23:39 · JFK 02:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.