简体   繁体   English

SQLAlchemy-如何生成仅返回jsonb列中的字段的查询

[英]Sqlalchemy - how do I generate a query that returns only a field from a jsonb column

I'm trying to find the best way to generate a sql query that gets me a specific field from a jsonb column from my db. 我试图找到生成sql查询的最佳方法,该查询从数据库的jsonb列中获取特定字段。 I want to generate a query like this: 我想生成这样的查询:

select images->'main' from scenes where id = 1;

I found this reference for using with_entities, and this generates the query correctly: 我发现参考使用了with_entities,并且可以正确生成查询:

>>> x = Scene.query.with_entities(Scene.images['main']).first()                                                                                                                                                                        
2016-09-22 18:57:01,825 INFO sqlalchemy.engine.base.Engine SELECT scenes.images -> %(images_1)s AS anon_1                                                                                                                              
FROM scenes                                                                                                                                                                                                                            
 LIMIT %(param_1)s                                                                                                                                                                                                                     
2016-09-22 18:57:01,826 INFO sqlalchemy.engine.base.Engine {'param_1': 1, 'images_1': 'main'}                                                                          

However, it's returning the result as a tuple rather than a model object: 但是,它以元组而不是模型对象的形式返回结果:

>>> x                                                                                                                                                                                                                                  
([{u'url': u'foo.jpg', u'priority': 1}],)        

I considered using load_only , but this API doesn't seem to have a way of specifying jsonb fields of a column, but only an entire column name. 我考虑过使用load_only ,但是此API似乎没有办法指定列的jsonb字段,而只能指定整个列的名称。

Is there a way to generate the query and have the model object as the return value? 有没有一种方法可以生成查询并将模型对象作为返回值?

Assuming that Scene is an ORM class, you can use Session.query() to either return the value as a tuple 假定Scene是ORM类,则可以使用Session.query()将值作为元组返回

x = session.query(Scene.images['main']).filter_by(id=1).one()
print x
SELECT images->'main' FROM scenes WHERE id = 1;

or the model object (instance of Scene ) 或模型对象( Scene实例)

scene = session.query(Scene).filter_by(id=1).one()
print scene.images['main']
SELECT * FROM scenes WHERE id = 1;
x = db.session.query(Scene.images['main'].label('main_image')).first()
print(x.main_image)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM