我在语法上做了一些愚蠢的错误,但无法弄清楚是什么。
我正在尝试使用 sqlalchemy func
来比较DB字段和变量,方法是将它们都放在较小的情况下,但是输出变为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>]
数据库:
+----+-----------------+--------------------------------------------------+------------+
| id | question | answer | created_at |
+----+-----------------+--------------------------------------------------+------------+
| 1 | Hi | Hey, Here I am and here you are. How can I help? | NULL |
| 2 | Hello | Hey, Here I am and here you are. How can I help? | NULL |
| 3 | Helo | Hey, Here I am and here you are. How can I help? | NULL |
| 4 | Heelo | Hey, Here I am and here you are. How can I help? | NULL |
| 5 | Hell | Hey, Here I am and here you are. How can I help? | NULL |
| 6 | Hallo | Hey, Here I am and here you are. How can I help? | NULL |
| 7 | Hey | Hey, Here I am and here you are. How can I help? | NULL |
| 8 | He | Hey, Here I am and here you are. How can I help? | NULL |
| 9 | Ho | Hey, Here I am and here you are. How can I help? | NULL |
| 10 | I need help | Hey, Here I am and here you are. How can I help? | NULL |
| 11 | Help | Hey, Here I am and here you are. How can I help? | NULL |
| 12 | can you help me | Hey, Here I am and here you are. How can I help? | NULL |
| 13 | Greetings | Hey, Here I am and here you are. How can I help? | NULL |
+----+-----------------+--------------------------------------------------+------------+
PS:
print QuestionsAndAnswers.query.filter(func.lower(QuestionsAndAnswers.question) == func.lower(question))
给出了这个:
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())
答案 0 :(得分:1)
问题是MySQL运行LOWER()
和UPPER()
cannot handle binary string types并且只返回未修改的二进制字符串。
正如相关专栏
question = Column(MEDIUMBLOB, nullable=False)
是二进制字符串类型,函数应用程序
func.lower(QuestionsAndAnswers.question)
是无操作,将按原样返回二进制字符串。这意味着比较将在&#34;嘿&#34;之间进行。和&#34;嘿&#34;并且谓词不匹配。
正确的解决方法是更改模型,表格和数据以使用适当的文本类型,例如Unicode
和UnicodeText
,但快速解决方案是添加强制转换:
from sqlalchemy import Unicode, cast
func.lower(cast(QuestionsAndAnswers.question, Unicode))