Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating columns at query level in sqlalchemy

Is it possible to combine two columns when querying in sqlalchemy?

For example, I have following table:

table 1                      table 2
col1   col2   col3           col1   col2  col3
A       123     1             ABC    A1B2
B       456     2             DEF    C3D4
C       789     3             GHI    E5F6

I would like my query to look something like this:

 session.query(table.col3, (table1.col2 + table2.col2)).join(table2)

And would like the following results:

(1, 123A1B2)
(2, 456C3D4)
(3, 789E5F6)

How would I go about doing that?

like image 210
JoeMicro Avatar asked Jun 23 '13 22:06

JoeMicro


1 Answers

It of course depends on db, and types; if the table1.col2 is a number, then you might want to try:

from sqlalchemy.sql import expression, functions
from sqlalchemy import types

... functions.concat(
    expressions.cast(table1.col2, types.Unicode), table2.col2) ...

Normally, + operator should work for 2 text columns.

like image 112