与 SQLAlchemy 不区分大小写的完全匹配

Case-insensitive exact match with SQLAlchemy

如何确保 = 运算符始终不区分大小写?与 LOWERUPPER 函数进行比较是性能的最佳选择吗? ILIKE好像很慢。

如果您只需要不区分大小写,请使用 upperlower,因为 like 不是仅关于不区分大小写

较低的示例:

my_string = 'BarFoo'
session.query(Foo).filter(func.lower(Foo.bar) == my_string.lower()).all()

在此处 how to execute LIKE query in sqlalchemy?

查看有关 like 的更多信息

不区分大小写的比较,可以subclass Comparator.

Building Custom Comparators

下面的示例 class 允许对名为 word_insensitive:

的属性进行不区分大小写的比较
    from sqlalchemy.ext.hybrid import Comparator, hybrid_property
    from sqlalchemy import func, Column, Integer, String
    from sqlalchemy.orm import Session
    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()

    class CaseInsensitiveComparator(Comparator):
        def __eq__(self, other):
            return func.lower(self.__clause_element__()) == func.lower(other)

    class SearchWord(Base):
        __tablename__ = 'searchword'
        id = Column(Integer, primary_key=True)
        word = Column(String(255), nullable=False)

        @hybrid_property
        def word_insensitive(self):
            return self.word.lower()

        @word_insensitive.comparator
        def word_insensitive(cls):
            return CaseInsensitiveComparator(cls.word)

上面,针对word_insensitive的SQL表达式将对双方应用LOWER() SQL函数:

    >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks")
    SELECT searchword.id AS searchword_id, searchword.word AS searchword_word FROM searchword
    WHERE lower(searchword.word) = lower(:lower_1)

上面的CaseInsensitiveComparator实现了ColumnOperators接口的一部分。使用 Operators.operate():

可以将类似小写的“强制”操作应用于所有比较操作(即 eqltgt 等)
    class CaseInsensitiveComparator(Comparator):
        def operate(self, op, other):
            return op(func.lower(self.__clause_element__()), func.lower(other))