SQLAlchemy中filter()和filter_by()有什么区别

47次阅读

有人能给我解释以下么,看不出又什么区别呢?

Toon

用法不同而已,filter 可以像写 sql 的 where 条件那样写 > < 等条件,但引用列名时,需要通过 类名.属性名 的方式。 filter_by 可以使用 python 的正常参数传递方法传递条件,指定列名时,不需要额外指定类名。,参数名对应名类中的属性名,但似乎不能使用 > < 等条件。

各有所长吧。

http://docs.sqlalchemy.org/en/rel_0_7…

greatghoul

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’)

zhuwei05

确实,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

von

感觉楼上的不是很对
filter指定列名的时候,可以不使用类名;filter_by也不是说任何时候都可以不指定类名
我平时使用的时候,两者区别主要就是当使用filter的时候条件之间是使用“==”,fitler_by使用的是”=”。
user1 = session.query(User).filter_by(id=1).first()
user1 = session.query(User).filter(id==1).first()

zwan0518

看源码,就两行,很清楚啊。

    def filter_by(self, **kwargs):
        """apply the given filtering criterion to a copy
        of this :class:`.Query`, using keyword expressions.

        e.g.::

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

        Multiple criteria are joined together by AND::

            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 :meth:`.Query.join`.

        .. seealso::

            :meth:`.Query.filter` - filter on SQL expressions.

        """

        clauses = [_entity_descriptor(self._joinpoint_zero(), key) == value
                   for key, value in kwargs.items()]
        return self.filter(sql.and_(*clauses))

filter_by()就是把你传参的key,value写成filter的sql格式,再加个and组合起来而已。

seethedoor

正文完