如何使用sqlalchemy从中文字符列进行搜索?

时间:2016-08-06 00:42:09

标签: python flask sqlalchemy

代码

result=Minicomputer.query.filter_by(u'名称'='CC670a').first()

错误

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    app = create_app(os.getenv('FLASK_CONFIG') or 'default')
  File "/mnt/hgfs/python/flask/Project/__init__.py", line 34, in create_app
    from .main import main as main_blueprint
  File "/mnt/hgfs/python/flask/Project/main/__init__.py", line 3, in <module>
    from . import views, errors
  File "/mnt/hgfs/python/flask/Project/main/views.py", line 95
    result=Minicomputer.query.filter_by(u'名称'='CC670a').first()
SyntaxError: keyword can't be an expression

小型机是使用中文字符列名

的表
engine = create_engine('mysql://root:1qaz2wsx@localhost/chhai?charset=utf8', convert_unicode=True, echo=False)
Base = declarative_base()
Base.metadata.reflect(engine)
db_session = scoped_session(sessionmaker(bind=engine))
Base.query = db_session.query_property()

class Storage(Base):

__table__ = Base.metadata.tables['storage']

def __repr__(self):
    return '<Storage %r>' % self.Storage_Name
class Minicomputer(Base):

__table__ = Base.metadata.tables['minicomputer']

def __repr__(self):
    name = u'名称'
    return '<Minicomputer %r>' % self.ID

2 个答案:

答案 0 :(得分:0)

filter_by是一个接受关键字参数的函数。 filter是一个接受表达式的函数。所以,要么

Minicomputer.query.filter_by(名称='CC670a')

Minicomputer.query.filter(Minicomputer.名称 == 'CC670a')

顺便说一句,你需要使用Python 3才能使用它,因为Python 2不允许使用非ASCII标识符。

答案 1 :(得分:0)

执行列映射解决了此错误

class Minicomputer(Base):
    __table__ = Base.metadata.tables['minicomputer']
    name = __table__.c[u'名称']


    def __repr__(self):

        return '<Minicomputer %r>' % self.name