Python Can';t获取SQLAlchemy func.lower以使用MySQL
我在语法上犯了一些愚蠢的错误,但不知道是什么 我试图使用sqlalchemyPython Can';t获取SQLAlchemy func.lower以使用MySQL,python,flask,sqlalchemy,flask-sqlalchemy,Python,Flask,Sqlalchemy,Flask Sqlalchemy,我在语法上犯了一些愚蠢的错误,但不知道是什么 我试图使用sqlalchemyfunc来比较DB字段和变量,方法是在小写情况下将它们都转换为null,但输出为null,就好像条件不满足一样 如果我不使用func并传递一个静态变量,同样的事情也会发生 守则: question = "Hey" q1 = QuestionsAndAnswers.query.filter(func.lower(QuestionsAndAnswers.question) == func.lower(question)).a
func
来比较DB字段和变量,方法是在小写情况下将它们都转换为null,但输出为null,就好像条件不满足一样
如果我不使用func
并传递一个静态变量,同样的事情也会发生
守则:
question = "Hey"
q1 = QuestionsAndAnswers.query.filter(func.lower(QuestionsAndAnswers.question) == func.lower(question)).all()
q2 = QuestionsAndAnswers.query.filter(QuestionsAndAnswers.question == "Hey").all()
print "q1", q1
print "q2", q2
输出:
q1 []
q2 [<intercom_bot.models.QuestionsAndAnswers object at 0x7f1e2c7add50>]
附言:
给出了:
SELECT questions_and_answers.id AS questions_and_answers_id, questions_and_answers.question AS questions_and_answers_question, questions_and_answers.answer AS questions_and_answers_answer, questions_and_answers.created_at AS questions_and_answers_created_at
FROM questions_and_answers
WHERE lower(questions_and_answers.question) = lower(:lower_1)
PPS:这是模型
class QuestionsAndAnswers(Base):
"""docstring for QuestionsAndAnswers"""
__tablename__ = 'questions_and_answers'
id = Column(BIGINT, primary_key=True)
question = Column(MEDIUMBLOB, nullable=False)
answer = Column(MEDIUMBLOB, nullable=False)
created_at = Column(DATETIME, nullable=True,
default=datetime.datetime.now())
问题是MySQL函数
LOWER()
和UPPER()
只返回未修改的二进制字符串
作为讨论中的专栏
question = Column(MEDIUMBLOB, nullable=False)
是一个二进制字符串类型,函数应用程序
func.lower(QuestionsAndAnswers.question)
是no操作,将按原样返回二进制字符串。这意味着比较将在“Hey”和“Hey”之间进行,谓词将不匹配
正确的解决方案是修改模型、表格和数据,以使用适当的文本类型,如和,但快速解决方案是添加强制转换:
from sqlalchemy import Unicode, cast
func.lower(cast(QuestionsAndAnswers.question, Unicode))
如果您使用
==question.lower()
,它是否有效?请尝试检查查询本身:打印(questionsandsanswers.query.filter(func.lower(questionsandsanswers.question)==func.lower(question))
,并查看是否显示任何奇怪的内容。此外,您是否正在使用MySQL?question
属性是二进制字符串吗。至少你在使用python 2,所以“嘿”
是一个字节字符串,所以func.lower(问题)
无效(没有操作),我想。试试这个:print db.session.query(func.lower(问题)).scalar()。你得到的是“嘿”
还是“嘿”
(这里听起来像克鲁斯提…)。事实上,如果两者都无效,它应该匹配,因为“嘿”==“嘿”
。。。所以两者都要检查。
func.lower(QuestionsAndAnswers.question)
from sqlalchemy import Unicode, cast
func.lower(cast(QuestionsAndAnswers.question, Unicode))