SQLAlchemy中filter()和filter_by()的区别

1、filter引用列名时,使用“类名.属性名”的方式,比较使用两个等号“==”

2、filter_by引用列名时,使用“属性名”,比较使用一个等号“=”

3、在使用多条件匹配的时候,filter需要借助sqlalchemy里的and_ ; 而filter_by不需要,直接把多个匹配条件写在一起

4、在使用多条件匹配时,用到>=、>、<=、<的情况,貌似不能使用filter_by。可能是姿势不对

 

参考

filter(*criterion)

apply the given filtering criterion to a copy of this Query, using SQL expressions.

e.g.:

session.query(MyClass).filter(MyClass.name == 'some name')

Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the and_() function:

session.query(MyClass).\
    filter(MyClass.name == 'some name', MyClass.id > 5)

The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the text() construct.

See also

Query.filter_by() - filter on keyword expressions.

filter_by(**kwargs)

apply the given filtering criterion to a copy of this Query, using keyword expressions.

e.g.:

session.query(MyClass).filter_by(name = 'some name')

Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the and_() function:

session.query(MyClass).\
    filter_by(name = 'some name', id = 5)

The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to Query.join().

See also

Query.filter() - filter on SQL expressions.

 

posted @ 2017-06-15 17:20  脚本小娃子  阅读(2074)  评论(0编辑  收藏  举报