zoukankan      html  css  js  c++  java
  • SQLAlchemy中filter()和filter_by()有什么区别

    from:https://segmentfault.com/q/1010000000140472

    filter:

    apply the given filtering criterion to a copy of this Query, using SQL expressions.
    e.g.:
    session.query(MyClass).filter(MyClass.name == 'some name')

    filter_by:

    apply the given filtering criterion to a copy of this Query, using keyword expressions.
    e.g.:
    session.query(MyClass).filter_by(name = 'some name')

    确实,filter用类名.属性名,比较用==,filter_by直接用属性名,比较用=
    不过这个是语法小细节。

    个人觉得最重要的区别是filter不支持组合查询,只能连续调用filter来变相实现。
    而filter_by的参数是**kwargs,直接支持组合查询。
    比如:

    q = sess.query(IS).filter(IS.node == node and IS.password == password).all()
    对应的sql是

    SELECT tb_is.id AS tb_is_id, tb_is.node AS tb_is_node, tb_is.password AS tb_is_password, tb_is.email AS tb_is_email, tb_is.`admin` AS tb_is_admin, tb_is.contact AS tb_is_contact, tb_is.is_available AS tb_is_is_available, tb_is.is_url AS tb_is_is_url, tb_is.note AS tb_is_note 
    FROM tb_is 
    WHERE tb_is.node = %(node_1)s

    and后面的条件既不报错,又不生效,很坑

    要实现组合查询,要么连续调用filter:
    q = sess.query(IS).filter(IS.node == node).filter(IS.password == password).all()

    或者直接用filter_by:
    q = sess.query(IS).filter_by(node=node, password=password).all()

    两者都对应sql:

     
    SELECT tb_is.id AS tb_is_id, tb_is.node AS tb_is_node, tb_is.password AS tb_is_password, tb_is.email AS tb_is_email, tb_is.`admin` AS tb_is_admin, tb_is.contact AS tb_is_contact, tb_is.is_available AS tb_is_is_available, tb_is.is_url AS tb_is_is_url, tb_is.note AS tb_is_note 
    FROM tb_is 
    WHERE tb_is.password = %(password_1)s AND tb_is.node = %(node_1)s
  • 相关阅读:
    luogu3242 接水果 (整体二分+树状数组)
    [BZOJ3449] [Usaco2014 Feb]Secret Code
    [BZOJ2821] 作诗(Poetize)
    [BZOJ2434] [Noi2011]阿狸的打字机
    [BZOJ1212] [HNOI2004]L语言
    [JZOJ100026]【NOIP2017提高A组模拟7.7】图
    [BZOJ2467] [中山市选2010]生成树
    [Luogu3868] [TJOI2009]猜数字
    [POJ1006] Biorhythms
    [BZOJ2733] [HNOI2012]永无乡
  • 原文地址:https://www.cnblogs.com/c-x-a/p/8521328.html
Copyright © 2011-2022 走看看