11

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i am using sqlite, table1.col2 is an int, table2.col2 is actually a date, but i want it to be a string, i just wanted to use it as a relationship unique id, in my query. but actually i realized that's not the way to go with what i am trying to do.. but never the less i was wondering about how to accomplish that, because in raw SQL it wouldn't be difficult. i would just do tbl1.col2 & tbl.col2 but in sqlalcehmy it returns TRUE. not sure why.
it returns true because & in sqlalchemy is the boolean and operator
Where is the documentation from this answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.