推荐学习书目
› 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 · Jul 21, 2016 · 3563 views
    This topic created in 3729 days ago, the information mentioned may be changed or developed.
    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 replies  •  2016-07-22 14:10:48 +08:00
    28ms
        1
    28ms  
       Jul 21, 2016
    用 raw sql 查比较方便
    stargazer
        2
    stargazer  
       Jul 21, 2016
    raw +1
    petelin
        3
    petelin  
       Jul 21, 2016 via Android
    raw+1 有些东西真的不能一次搞出来,必须得自己写
    hao1032
        4
    hao1032  
    OP
       Jul 21, 2016
    @28ms @petelin @petelin 大家说的 raw 指的是用 union all 吗?
    petelin
        5
    petelin  
       Jul 21, 2016 via Android
    @hao1032 应该是直接拼接 sql 语句吧,这个有点类似于分组取每组 top100
    Allianzcortex
        6
    Allianzcortex  
       Jul 22, 2016
    我也感觉直接拼, 上原生 sql,Google 上搜“ django model select different type ”没有什么太好的结果
    wph95
        7
    wph95  
       Jul 22, 2016
    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  
       Jul 22, 2016
    @hao1032 mysql 以外的的 RDMS 可以用 window function
    hao1032
        9
    hao1032  
    OP
       Jul 22, 2016
    @wph95 项目有 12w 数据且分布不定。这样的的做法效率也不高。
    hao1032
        10
    hao1032  
    OP
       Jul 22, 2016
    All 感谢大家的回复,最终决定新建立一个表,里面只保存各 type 最近的 100 个结果。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2331 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 10:39 · PVG 18:39 · LAX 03:39 · JFK 06:39
    ♥ Do have faith in what you're doing.