- changed status to resolved
.label() addition of two columns
I know it's possible to label an arbitrary column in a query:
session.query(Person.name.label("name"))
It isn't possible to do this:
session.query((Person.age + Person.wealth).label("sum"))
How would I go about labeling an addition of different columns?
Comments (8)
-
reporter -
repo owner please define "it isn't possible". There's no issue adding two columns and labeling them.
from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Person(Base): __tablename__ = 'a' id = Column(Integer, primary_key=True) age = Column(Integer) wealth = Column(Integer) e = create_engine("sqlite://") Base.metadata.create_all(e) s = Session(e) s.add(Person(age=5, wealth=10)) s.commit() row = s.query((Person.age + Person.wealth).label('sum')).first() print row.sum
output:
15
-
repo owner using literal_column is the wrong approach here when you have mapped columns to work with directly.
-
reporter Sorry Mike, I was in a rush and got another error which I thought had to do with this... Seems like your approach works perfectly.
What is the use case for literal columns?
-
repo owner when you want to write some SQL column expression that is not cleanly met by the existing constructs, like a constant,
literal_column("'TEXT'")
. -
reporter Oh, so syntax that is db specific?
-
@zzzeek What if I want to pick the columns to add dynamically from an array ?
-
repo owner columns[some_index_a] + columns[some_index_b]
? - Log in to comment
Solved it myself with literal_column
session.query(literal_column("col1 + col2").label("lbl"))