【问题标题】:quoting case sensitive column names in SQLAlchemy filter在 SQLAlchemy 过滤器中引用区分大小写的列名
【发布时间】:2013-10-02 07:55:01
【问题描述】:

我正在尝试在 SQLAlchemy (python) 中运行过滤器查询,但在列名中遇到了区分大小写的问题。

模型类是从模式中自动生成的,如下所示:

Base = declarative_base()
engine = create_engine('postgresql://user:pass@localhost:5432/database')
metadata = MetaData(bind=engine)

class MyTable(Base):
    __table__ = Table('my_table', metadata, autoload=True, quote=True)

这是我运行过滤器查询的方式:

val = 1
result = session.query(MyTable).filter("myCaseSensitiveAttribute=:myCaseSensitiveAttribute").params(myCaseSensitiveAttribute=val).all()

这会导致错误:

sqlalchemy.exc.ProgrammingError: (ProgrammingError) 列“mycasesensitiveattribute”不存在 第 3 行:其中 myCaseSensitiveAttribute=1

在区分大小写的情况下,其他一切都可以正常工作。只有过滤器会导致问题。有没有办法强制它引用列名而不显式定义模型类中的每个属性(在这种情况下不实用),或者基于变量值过滤结果集的其他一些工作方法?

感谢您的宝贵时间!

【问题讨论】:

    标签: filter sqlalchemy case-sensitive


    【解决方案1】:

    如果您使用的是文字 SQL,则 quote=True 与发生的事情无关。 SQLAlchemy 只负责在使用 Table 和 Column 对象而不是字符串来呈现 SQL 时进行引用。使用这些时,在绝大多数情况下,仍然不需要 quote=True,因为 SQLAlchemy Core 表达式构造会自动处理区分大小写的标识符。

    示例,说明几种用法:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    engine = create_engine('postgresql://scott:tiger@localhost:5432/test')
    conn = engine.connect()
    trans = conn.begin()
    
    conn.execute('create table "SomeCaseTable" ("SomeAttribute" varchar(20) primary key)')
    conn.execute('''insert into "SomeCaseTable" ("SomeAttribute") values ('some data')''')
    metadata = MetaData(bind=conn)
    
    class MyTable(Base):
        __table__ = Table('SomeCaseTable', metadata, autoload=True)
    
    session = Session(conn)
    val = 'some data'
    
    # example 1: use SQL expressions
    print(
        session.query(MyTable).
            filter(MyTable.SomeAttribute == val).
            all()
    )
    
    # example 2: totally literal SQL - you need to quote manually
    print(
        session.query(MyTable).
            filter('"SomeAttribute"=:some_attribute').
            params(some_attribute=val).all()
    )
    
    # example 3: bound param with SQL expressions
    print(
        session.query(MyTable).
            filter(MyTable.SomeAttribute == bindparam('somevalue')).
            params(somevalue=val).all()
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 2013-08-07
      • 2023-04-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多