kdwycz
54.12D
11.47D
V2EX  ›  Django

关于 django model 的 get 和 filter 方法效率差距

  •  
  •   kdwycz ·
    kdwycz · Jul 17, 2015 · 6212 views
    This topic created in 3985 days ago, the information mentioned may be changed or developed.

    如果知道取的值是唯一的,但不一定存在

    是使用get检查异常好,还是使用filter看是否存在好?

    从程序运行效率的角度讲

    9 replies    2015-07-17 21:46:15 +08:00
    socrates
        1
    socrates  
       Jul 17, 2015   ❤️ 1
    貌似不是用get 和filter比,而是get和first比更适合

    get相当于加了一个limit(2)在里面,如果有重复或者不存在会抛异常,first()相当于limit(1),比get效率要高一些
    magine
        2
    magine  
       Jul 17, 2015   ❤️ 1
    使用first()更好,但是要注意first()不会抛出异常,找不到只会返回None。
    顺便一说咱们公司的代码用的是Django1.5.6,first在1.6才有...
    所以你还是用get吧...
    kdwycz
        4
    kdwycz  
    OP
       Jul 17, 2015
    @magine 好吧...刚才去shell里面没发现first
    ericls
        5
    ericls  
       Jul 17, 2015
    使用 exists() 检查是否存在!
    sunus
        6
    sunus  
       Jul 17, 2015   ❤️ 1
    看下django issue出来的sql就知道了
    magine
        7
    magine  
       Jul 17, 2015
    @kdwycz
    我给你的建议是早期设计不要想太多...
    实现功能后再慢慢找性能瓶颈,过早优化是万恶之源。
    latyas
        8
    latyas  
       Jul 17, 2015
    都是执行一条SQL,瓶颈永远在数据库IO上
    virusdefender
        9
    virusdefender  
       Jul 17, 2015
    存在不存在 用 exists()
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   821 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 20:56 · PVG 04:56 · LAX 13:56 · JFK 16:56
    ♥ Do have faith in what you're doing.