常用代码
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, JSON
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer(), primary_key=True)
message = Column(JSON)
MySQL
JSON查询语句就这样清晰漂亮
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test', pool_recycle=3600) # MySQL
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
person = Person(message={'name': 'Bob'}) # Insert a record
session.add(person)
session.commit()
query = session.query(Person.id).filter(Person.message['name'] == 'Bob') # MySQL will work, clear and beautiful
print(query[0].id) # 1
print(query)
# SELECT person.id AS person_id
# FROM person
# WHERE JSON_EXTRACT(person.message, %(message_1)s) = %(param_1)s
SQLite
它使用了不必要的
json_quote()
并且结果不明确。我想用 JSON_QUOTE 关闭 sqlite json 查询。
我该如何解决这个问题?
engine = create_engine('sqlite:///:memory:') # SQLite
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
person = Person(message={'name': 'Bob'}) # Insert a record
session.add(person)
session.commit()
query = session.query(Person.id).filter(Person.message['name'] == func.json_quote('Bob')) # SQLite will work, but need to use json_quote
print(query[0].id) # 1
print(query)
# SELECT person.id AS person_id
# FROM person
# WHERE JSON_QUOTE(JSON_EXTRACT(person.message, ?)) = json_quote(?)
我也遇到了同样的问题。如果您调用
as_string()
方法,则会删除 SQLite 的 json_quote 调用。
query = session.query(Person.id).filter(Person.message['name'].as_string() == 'Bob')