SQLAlchemy学习-8.query查找之filter()和filter_by()区别

前言

SQLAlchemy 使用query查询的时,可以使用filter()和filter_by() 过滤条件。
filter_by() 参数直接用属性名,比较用一个=
filter() 参数 用类名.属性名,比较用 ==

filter_by() 语法

filter_by() 源码如下

    def filter_by(self, **kwargs):
        r"""Apply the given filtering criterion to a copy
        of this :class:`_query.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 :func:`.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 :meth:`_query.Query.join`.

        .. seealso::

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

        """
        from_entity = self._filter_by_zero()
        if from_entity is None:
            raise sa_exc.InvalidRequestError(
                "Can't use filter_by when the first entity '%s' of a query "
                "is not a mapped class. Please use the filter method instead, "
                "or change the order of the entities in the query"
                % self._query_entity_zero()
            )

        clauses = [
            _entity_namespace_key(from_entity, key) == value
            for key, value in kwargs.items()
        ]
        return self.filter(*clauses)

从源码可以看出,filter_by() 封装了 filter() 方法,参数接受键值对的关键字参数**kwargs

主要区别

模块 参数 大于(>)和小于(<) and_、or_、like、in_
filter_by() 直接用属性名,比较用= 不支持 不支持
filter() 用类名.属性名,比较用== 支持 支持

filter_by() 使用示例

filter_by() 只能筛选条件等于,不支持 大于 (>)和小于 (<)和 and_、or_查询

session.query(Students).filter_by(name='yoyo').all()

如果需要满足多个条件,查询name名称等于'yoyo', 并且年龄age等于20,中间用逗号隔开

session.query(Students).filter_by(name='yoyo', age=20).all()

等价于filter查询

db.session.query(Students).filter(Students.name == 'yoyo').all()
db.session.query(Students).filter(Students.name == 'yoyo', Students.age == 20).all()

filter() 示例

filter() 除了可以支持判断等于,还可以支持 大于 (>)和小于 (<)和 and_、or_、like、in_查询


# 大于 >
session.query(Students).filter(Students.age > 20).all()

# 小于 <

session.query(Students).filter(Students.age < 20).all()

# and_ 查询
session.query(Students).filter(and_(Students.name == 'yoyo', Students.age == 20)).all()

# or_查询
session.query(Students).filter(or_(Students.id >= 1, Students.name == 'yoyo')).all()

# like 模糊匹配
session.query(Students.name).filter(Students.name.like('%yoyo%')).all()

# _in包含

session.query(Students.name).filter(Students.name.in_(['yoyo', 'yoyo1'])).all()

filter更多查询参考https://www.cnblogs.com/yoyoketang/p/16477058.html

posted @ 2022-07-17 16:26  上海-悠悠  阅读(2367)  评论(0编辑  收藏  举报