如何在 sqlalchemy 查询中选择文字值? [英] How do I select literal values in an sqlalchemy query?
问题描述
我有一个看起来像这样的查询:
I have a query which looks like this:
query = session.query(Item) \
.filter(Item.company_id == company_id) \
.order_by(Item.id)
这是一个非常基本的查询.除了提取 Item 的值之外,我还想在组合中附加一个附加值,并将其返回给我.在原始 SQL 中,我会这样做:
It's a pretty basic query. In addition to pulling out the values for the Item, I want to append an additional value into the mix, and have it returned to me. In raw SQL, I would do this:
SELECT *, 0 as subscribed
FROM items
WHERE company_id = 34
ORDER BY id
如何通过 sqlalchemy 手动添加该值?
How can I manually add that value via sqlalchemy?
推荐答案
您需要使用 literal_column
,看起来有点像这样:
You'll need to use a literal_column
, which looks a bit like this:
sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.literal_column("0"))
请注意 text
参数是在没有任何转换的情况下插入到查询中的;如果您从应用程序外部接受文本参数的值,这可能会使您面临 SQL 注入漏洞.如果这是你需要的东西,你会想要使用 bindparam
,使用起来也差不多;但你必须创造一个名字:
Beware that the text
argument is inserted into the query without any transformation; this may expose you to a SQL Injection vulnerability if you accept values for the text parameter from outside your application. If that's something you need, you'll want to use bindparam
, which is about as easy to use; but you will have to invent a name:
sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.bindparam("zero", 0))
这篇关于如何在 sqlalchemy 查询中选择文字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!