kdwycz
54.12D
12.21D
V2EX  ›  Django

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

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

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

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

    从程序运行效率的角度讲

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

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