How do I select literal values in an sqlalchemy query?

前端 未结 2 1581
清歌不尽
清歌不尽 2020-11-27 06:16

I have a query which looks like this:

query = session.query(Item) \\
    .filter(Item.company_id == company_id) \\
    .order_by(Item.id)

I

相关标签:
2条回答
  • 2020-11-27 06:32

    You'll need to use a literal_column, which looks a bit like this:

    sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.literal_column("0"))
    

    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))
    
    0 讨论(0)
  • 2020-11-27 06:46

    As mentioned in the comments of the accepted answer there's a "shorthand" for bindparam() that alleviates the need to come up with a name for the literal bindparam, literal():

    Return a literal clause, bound to a bind parameter.

    So one does not have to write

    session.query(Item, bindparam("zero", 0).label("subscribed"))
    

    but just

    session.query(Item, literal(0).label("subscribed"))
    

    without having to worry about quoting etc., if passing strings or such.

    0 讨论(0)
提交回复
热议问题