.label() addition of two columns

Issue #3272 resolved
Dani Hodovic created an issue

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)

  1. Mike Bayer 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

  2. Mike Bayer repo owner

    using literal_column is the wrong approach here when you have mapped columns to work with directly.

  3. Dani Hodovic 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?

  4. Mike Bayer 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'").

  5. Log in to comment