lundi 21 mars 2016

How to concat columns in sqlalchemy ORM with separator platform independently?

Here is the query right now. As you can see from using outerjoin some of the values could be None. What I need to do is sort the output alphabetically and then concatenate it with separator to a one string.

q = session.query(B.name, C.name, D.title, G.value_en).\
        join(A, A.id == B.a_id).\
        join(C, C.id == A.b_id).\
        outerjoin(D, D.id == B.emitent_id).\
        outerjoin(
            G,
            and_(
                G.b_id == B.id,
                G.j_id == J.id
            )
        ).\
        outerjoin(J)

I can do that in python of course, but I'd like to know if there is a way to do that in query. I've read about func.concat, but session.query(func.concat(...)) gives

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such function: concat

Production db is mysql and I'm using sqlite for testing. And don't tell me to use one database for production and testing, ok?

1 commentaire:

  1. 5 years later. Got the same problem.
    Solved it by using the Column level concat:
    https://docs.sqlalchemy.org/en/13/core/metadata.html?highlight=concat#sqlalchemy.schema.Column.concat

    session.query(B.name.concat(C.name))

    RépondreSupprimer