Query-level column concatenation in sqlalchemy

It is possible to combine two columns when querying in sqlalchemy.

ex, have the 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 

my query would be something like this:

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

and should give me the following results:

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

how would i do that?

+4
source share
1 answer

This, of course, depends on db and types; if table1.col2 is a number, you can try:

 from sqlalchemy.sql import expression, functions from sqlalchemy import types ... functions.concat( expressions.cast(table1.col2, types.Unicode), table2.col2) ... 

Normally, the + operator should work for two text columns.

+3
source

Source: https://habr.com/ru/post/1487772/


All Articles