【发布时间】:2019-04-15 06:50:48
【问题描述】:
我有json column 的模型。模型和数据示例:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://...'
db = SQLAlchemy()
db.init_app(app)
app.app_context().push()
class Example(db.Model):
id = db.Column(db.Integer(), nullable=False, primary_key=True, )
json_field = db.Column(db.JSON())
db.create_all()
db.session.add(Example(json_field={'id': None}))
db.session.add(Example(json_field={'id': 1}))
db.session.add(Example(json_field={'id': 50}))
db.session.add(Example(json_field={}))
db.session.commit()
现在我尝试查找id == 1:
query = db.session.query(Example).filter(Example.json_field['id'] == 1)
print(query.all())
我得到下一个错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) 运算符 不存在:json = integer LINE 3: WHERE (example.json_field -> 'id') = 1
原因。查看生成的查询:
SELECT example.id AS example_id, example.json_field AS example_json_field
FROM example
WHERE (example.json_field -> %(json_field_1)s) = %(param_1)s
但在我的情况下,正确的查询应该是这样的:
SELECT * FROM example WHERE CAST(json_field->>'id' AS INTEGER) = 1;
我该怎么做?
我尝试过使用cast,但没有成功:
print(
db.session.query(Example).filter(
cast(Example.json_field['id'], Integer) == 1
).all()
)
错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) 不能 将类型 json 转换为整数 LINE 3: WHERE CAST((example.json_field -> 'id') 作为整数) = 1
如您所见,where clause 仍然是错误的。我还需要使用范围(>、<= 等)条件。感谢您的帮助。
【问题讨论】:
标签: python sqlalchemy flask-sqlalchemy